The official Fatica Labs Blog! RSS 2.0
# Tuesday, 12 February 2013

I’ve noticed that sometimes when developer want to embed in they own infrastructure an external library they feel the needing of encapsulate that dependency in a common-versus-tool library. So we have a plethora of, just for say CommonLogging, CommonIoC, CommonOrm and so on, every one claiming the ability of “Just Plug The Tool”.

I would like to try to show why this is a tremendously ugly antipattern in my opinion, by showing the side effects of this approach, and alternative solutions.

 

1.CommonIoC or CommonServiceLocator (squared antipattern) 

The first impressive attempt is trying to insulate the IoC kernel we want to use. So instead on having the application depending on the IoC, we just have the App depending on the CommmonThing, we do some work in creating it, we have back nothing but a boring piece of code to maintain. The spectacular attempt is when the encapsulated guy is the service locator, that guy kill  by its own the entire effort in code decoupling, make component dependency obscure to everyone else but the developer who code the component in the first week. So creating the common layer  just multiply the side effects and the result is a squared antipattern that scares any reasonable professional.

The solution: In this case there is a pattern that is a real silver bullet : Composition Root. Just have the IoC used in a single point and have it’s effect propagating trough all the application by using the proper IoC features: Inject into constructors, use factories and have the IoC effect recursively propagate among all the application without referring directly the kernel. In the root, use all the IoC features you have, by not having the common thing around you, you have no lowest common denominator to deal with. If you want to change the IoC in the future, you completely rewrite this single file, and you will use all the new kernel features. You must avoid using byzantine attributes for injecting your properties, if the IoC you mind to use need them, is not the correct one. A side effect of this approach could be an increasing amount of factories class. While this could be considered a problem some IoC offer some sort of automatic factories, out of the box or with additional plugin. I’m not sure if they help or not, i fear that code became too magic, and this will possibly violate the “Coding For a Violent Psycopaths” principle. As a least consideration: IoC is for applications, it is not for libraries. If you are writing an infrastructure reusable component, you must not base it on any IoC strategy. Things are a little different if you are creating a framework, and this framework leverages and offer services when an IoC exist in the hosting application. Even in this case, instead of creating a common thing, the framework should provide its own IoC abstraction, and the hosting application must provide an adapter to the IoC currently used. The framework abstraction  must be designed in order to fully satisfy the framework requirements, leaving the adapter implementer the challenge its own IoC. A good example of a framework using the described strategy is Caliburn Micro.

 

2.Common logging

Since every good appealing applications logs, this is a real temptation for the CommonLogging beast. Even not considering the fact that the logging libraries used in production are about two, why we need this? Please enumerate how many time you decide to drop a logger in favour of another, end eve if this was the case, was really this refactoring time jeopardizing the project? Another danger coming from the CommonBeast here is the fact that being such a library “too small” to be justified, it can possibly collapse in another anti pattern: “The enterprise magic library”, a library containing a set of more or less useful thing that every developer want to maintain when new stuff has to be added, and no one feel responsible when it breaks.

The solution: Is the same as above: define the logging interface in the library, and let the application implement it. A great example on this comes form NHibernate. NH was strictly bound with log4net till version 3.xxx, starting from there you can implement its own abstract logging interface. Beautiful to have, NH uses log4net as a default by dynamically loading it (  eliminating the needing of having log4net at compile time ) degrading gracefully to the old behavior.  

3.Common OR/M

This is probably the worst. An OR/m already introduce a sensible impedance toward the database, adding an home made abstraction layer pretending to deal wit NH, EF add another multiplying impedance to your application. Writing an application that leverages an OR/M is usually a collection of best practices that OR/M imposes to make the data access as faster as possible. Such trick are usually difficult to abstract and you don’t know a lot of them until you face it.

The solution: First solution is don’t do it at all. it is not a so strange scenario to choose the or/m you want to use in the design phase, and bring it to production and maintenance simply with that or/m. By the way software makes money when it does what the customer want, not when is modified to follow the latest trend in data access. Another less strict solution is to use the “query object pattern”, that does not mean implement your ad hoc query provider, but means encapsulate each aggregates operation in single classes responsible for all the data access, exposing proper and useful methods to refine the query specialized for the aggregate. This allow a conceptually easy refactoring if we want to change the OR/M. And by the way in an every day experience scenario, you mostly don’t swap NH or EF, but more probably you want to change some of your query object to use some micro OR/m  for performance reason.

 

The example series could be extended to the same degree of utility libraries we use. A CommonMessaging the first one comes in mind.The point is that the “CommonThing” is a worst practice, it gives us no advantages but just pain and problems, so use all the effort to avoid it and focalize into the real problem.

Tuesday, 12 February 2013 08:37:14 (GMT Standard Time, UTC+00:00)  #    Comments [0] - Trackback
Programming | pattern

# Friday, 27 April 2012

I described the “typed factory” concept here some days ago. The solution we looked at was requiring the Castle DynamicProxy dependency. If you want something simpler zero dependency and “just working” I creted a little hacking factory: AnyFactory. It is really simple and does not requires any external dependency, and can be integrated in your project by just adding a single file. I provided some documentation on the project wiki. The extension works by crafting a factory implementation using Reflection.Emit. It does not requires to configure anything since a unresolved dependency satisfying some restrictive rule is considered to be a factory, and the implementation is produced in the background.

the rules for an interface to be consider a factory are:

  • It is a public interface
  • Each method name starts with Create
  • Each method return something
  • There is no properties

The name is required to begin with Create, if it contains something after Create, this is considered to be a named binding to solve. Construction parameters can be specified, but there is a restriction: the parameter name should match the implementation constructor parameter name. ANother limitation is that we don’t support the “delegate” factory.

Friday, 27 April 2012 16:54:54 (GMT Daylight Time, UTC+01:00)  #    Comments [0] - Trackback
C# | Programming

# Wednesday, 25 April 2012

Yesterday I had an interesting discussion with a colleague about using IoC in the real world in a proper way, without falling back in the Service Locator Antipattern, and of course without having a reference to the container, that is just so horrible to not worth any word. So we both found the solution being the use of factories, supplied by the container, to create the on-the-fly requested components. I was used to craft these factories by hand, but I know is a little silly, especially when the colleague talked about the Castle(Windsor) typed factories. So quite interesting, but since I choose NInject as my IoC ( Castle was the first container I saw, and my first love too ) I felt the challenge to implement the same but… Fortunately ( well, for say it would be nice being the implementer ) Remo Gloor provided a NInject extension that does almost the same for this other beautiful container. A nice documentation is also available on the Github repository. So thanks to a discussion I improved my programming knowledge, the Ninject.extensios.factoy is added to my toolbox A bocca aperta

Wednesday, 25 April 2012 15:58:04 (GMT Daylight Time, UTC+01:00)  #    Comments [0] - Trackback
CSharp | Programming

# Monday, 16 January 2012

Here below a list of tools and libraries I consider necessary to carry on my USB key in order to be operative everywhere in a very little time:

  1. SharpDevelop
  2. NHibernate
  3. Caliburn(Micro)
  4. NInject
  5. Kaxaml
  6. SQLite
  7. Rad Software Regular Expression Designer
  8. ILSpy
  9. FlyFetch
  10. log4net

SharpDevelop

Is probably the single OS replacement for MS Visual Studio. Install and start to using it in term of minutes thanks to xcopy deploy. It reads projects in the same format of the original one ( since it uses thestandard framework libraries for reading/writing projects ).

NHibernate

If you can see a way to model the DB you want to use, then NH is probably the best OR/M existing in the .NET environment. As soon you have some confidence with it, it is very easy to start modeling our objects, expecially with the 3.2.x version that does not require anymore to write hbms.

Caliburn Micro

If you write UI using some XAML dialect ( WPF/SILVERLIGHT/WP7/ the new coming Win8 ) and you like MVVM, you have to look at it. Very easy to boostrap, with coroutine support embedded, I would like to use it even for an Hello World application Smile

NInject

An easy to learn DI framework. Easy and very intuitive to configure, it has some function to allow multiple components to be injected as array, and to configure dependencies from external modules. I choose it not only, but also for the wonderful home page Smile

Kaxaml

A pad to learn and test XAML, with intellisense and preview as you type. Like xamlpad, but much better.

SQlite

An embedded file based database. It handles concurrent access consistently, easy to interface with NHibernate. Unfortunately it is a native solution, so it works only in fully trusted environments.

Rad Software Regular Expression Designer

there is a lot of regex testing tool, but this is the one I use, so…

ILSPy

The open source replacement for reflector, It comes from the same team who create SharpDevelop. It has all the features the standard reflector has, but not yet a real plugin environment.

FlyFetch

Is the tool I use when I need to display in UI a very long recordset, and I want to page it without rewrite every day the same code.

log4net

To use in all application, even the simplest: logManager.GetLogger(GetType()).Info(“Hello World”); Smile It is probably the .NET logger existing from the early days, with a lot of appenders already written and tested.

 

So this is my list, of course, another survival pre condition is having an internet access, and the StackOverflow help Smile. There is no NUnit nor a Mocking library ( as for example, Moq) since both can be replaced by custom test and mocks, but of course, if there is still place on the USB Winking smile

Monday, 16 January 2012 19:39:06 (GMT Standard Time, UTC+00:00)  #    Comments [0] - Trackback
CodeProject | Programming

My Stack Overflow
Contacts

Send mail to the author(s) E-mail

Tags
profile for Felice Pollano at Stack Overflow, Q&A for professional and enthusiast programmers
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2017
Felice Pollano
Sign In
Statistics
Total Posts: 157
This Year: 0
This Month: 0
This Week: 0
Comments: 124
This blog visits
All Content © 2017, Felice Pollano
DasBlog theme 'Business' created by Christoph De Baene (delarou) and modified by Felice Pollano