Square peg in a round Hole

After lots of year working with NHibernate I started to think that probably the whole concept of ORM can be considered an Antipattern. Some people prefer a “classic” approach to the problem, data is the key concept and most of the logic is inside a storage based on Relational Model.

Is this wrong?

Absolutely not, after all, for many years this was the preferred way to structure your application, and it worked quite well, but after OOP has come to life, a lot of people started appreciating this new paradigm of programming and started to think in terms of “objects” instead of “data”.

This is a radical shift, because if you really possess “object thinking”, you tend to subdivide the problem in objects that  have methods instead that in table that have relations. This lead to an obvious problem, since we need to store the data somewhere and since we already have good Relational Database Engine, the simplest solution is finding a way to save Objects in Relational Storage system and an ORM is the answer.

But after years of ORM the initial enthusiasm is completely passed away and I start believing that I’m forcing a square peg in a round hole.

Since most programmers started to work in terms of data and relations (after all university taught us to think in this way), using an ORM lead usually to highly anemic domain and tend to lead people of thinking in term of objects that have state (properties) and relations with other objects instead of object that have methods and communicates with other objects (with events).

If you start designing your entities from their state (properties) it could be the sign that you moved from “tables with relations and stored procedures that operates on tables” to “objects with relations and services that operates on objects”, and you need to realize that the situation is not changed very much.

When people start to have problems with Session duration, Lazy Loading, eager fetching (or other issue related to ORM), is the sign that the square peg is not fitting in the round hole and the ORM becomes the Hammer that forces it down (usually bringing some pain with it).

This means that if you want to do OOP you should move everything to NoSql?

Absolutely not, because sometimes you will probably find yourself forcing a round peg in a square hole :). I’m starting to think that in a real, big, complex OOP project, you need to have both type of storage: Relational and Object based. This will give you  round holes and the square holes, so you can put each peg in the right place.

At least until some new technology comes to life that bring us a new Hexagonal Peg :) that will need an Hexagonal shaped data storage Smile.

Gian Maria.

Leverage the concept of “state” of your entities

One of the interesting ideas found in Radical and other implementations of DDD architectures, is implementing properties of Domain objects in a slightly different way from the standard, using something like a dictionary to store values of properties. When we want to implement a property for a Domain class you usually end up with similar code.

   1: public String Property { get; set; }

   2:  

   3: private string _fieldBasedProperty;

   4: public String FieldBasedProperty

   5: {

   6:     get { return _fieldBasedProperty; }

   7:     set { _fieldBasedProperty = value; }

   8: }

Both of them use a private field to store the real value of the property, the first one is a compact form  (I to not like it for Domain object because it gives you no control on state changing of the object), the second one is the standard code to implement a property with a Backing field. Remember that in OOP an Object is a composition of Code and Data and having getter and setter for properties give use control on the state of the object. Both of the above implementations are based on this concept and are widely used in all projects.

But we could adopt another approach to enforce the concept of state of the object, making the concept of state emerge from the implementation. We start defining a State class.

image

This class is used to store values indexed by property names and will used to maintain the state of all entities. Thanks to this class we can define a BaseEntity class to implement some basic functionality that we want to share between all classes.

image

The most important methods are Get and Set methods, used by derived classes to manage change of state of the object. If you want to implement a simple property in a derived class, you will write this code.

   1: class Post : BaseEntity

   2: {

   3:     public String Title

   4:     {

   5:         get { return Get(() => Title);}

   6:         set { Set(() => Title, value);}

   7:     }

   8: }

The syntax used is strongly typed, thanks to static reflection, and delegates to base class state management, in this simple example base class implements the INotifyPropertyChanged, but you can implement all the logic you want.

This approach is really interesting, because it does not prevent you from using any technique you use with the standard property and state management, but leverage the concept of state in a consistent way. With standard property implementation, state is scattered across various fields of an entity, an approach that is not really DDD oriented; using an explicit concept (and a specific class) to manage state leverage the concept of encapsulation in a more explicit way and can lead to interesting solutions.

Alk.

Tags:

Lifecycle of singleton objects

Some days ago I blogged about an implementation of persistent cache component based on Managed Esent and PersistentDictionary. This component is injected into other components thanks to Inversion of Control and it is a Singleton object.

Being a singleton is a requisite because it permits to different dependent objects to share the same cache, moreover PersistentDictionary does not permit to have multiple instances that insists on the same directory. This will make EsentCache a perfect candidate of Singleton Object Pattern. Now another dilemma arise, since PersistentDictionary implements IDisposable to flush all resources into disk, who will call Dispose on a Singleton object?

The solution is obvious, this is a duty of the Inversion Of Control engine you use and this is another reason to base your architecture with Dependency Injection in mind. With a IoC container, being a singleton is a “property” of registered instance making the IoC container responsible of the lifecycle of the singleton. In my application there is a static IoC class (a service locator pattern) used by infrastructural code to create objects, based on Castle.Windsor container. Since a WindsorContainer is a Disposable object I want to be sure that it got disposed when the application exit.

   1: static IoC()

   2: {

   3:     AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);

   4:     BaseInitialization();

   5: }

Static constructor will set an handler for ProcessExit event of current domain. This event have a special purpose, as you can read in MSDN documentation

The EventHandler for this event can perform termination activities, such as closing files, releasing storage and so on, before the process ends.

The only drawback is that the execution time of this method is limited as explained in the documentation

Note:

The total execution time of all ProcessExit event handlers is limited, just as the total execution time of all finalizers is limited at process shutdown. The default is two seconds. An unmanaged host can change this execution time by calling the ICLRPolicyManager::SetTimeout method with the OPR_ProcessExit enumeration value.

This could be a problem, because shutting down the IoC engine will call dispose method for each singleton object that was resolved and we cannot anticipate how time this operation will need, but we have no other option to have a fallback technique to avoid people forgetting to call dispose on the IoC container.

The implementation of the event handler is really simple

   1: static void CurrentDomain_ProcessExit(object sender, EventArgs e)

   2: {

   3:     Shutdown();

   4: }

All work is delegated to the Shutdown() event, this will make possible for programs to dispose the IoC engine gracefully. For windows program you can simple put a call to Shutdown before the end of Main() method, this will pose no limit on Shutdown execution time, but if for some reason, people forgets to call Shutdown explicitly when the application is ending, resources will be released thanks to the ProcessExit event handler.

alk.

Mock, Service Locator and Automocking Container to the rescue

In a previous post I dealt on how to write an AutoMockingContainer that is able to resolve a mock for unregistered objects. The goal was to be able to circumvent the problem of service locator.

SNAGHTML1e24939

Figure 1: During a test, the real container of the service locator is substituted with an AutoMocking container.

This is a standard way to work when you have to test classes that depends from Service Locator, override the Service Locator for the test, making it returns stub. Clearly you should design your class with Dependency Injection in mind, and reduce at minimum the Service Locator usage.

Now consider a better version of the class to test

SNAGHTML1f30b02

Figure 2: A better way to structure the class, it does not use service locator, instead declares a non-optional dependency on the constructor

In Figure 2 BetterObjAnInterface class declares a non-optional dependency from ILogger, now to test that _logger.Debug() method gets called during the invocation of DoTest() method, you can write this code.

SNAGHTML1f6549e

Figure 3: Testing the interaction of a class with a dependent service.

Test in Figure 3 is really better that overriding the container of Service Locator but suffers from some problems. First, if someone changes the BetterObjAnInterface, make it depending from another interface, all the tests are broken, because you should modify them to create the other stubs to pass in the constructor. Another problem is: if the SUT declares a lot of dependency, test code is full of MockRepository.GenerateStub() call to satisfy all non optional dependencies and the test become harder to read.

The solution is again in the AutoMockingcontainer object. Thanks to Castle Windsor Extendibility, you can write a SubDependencyResolver that actually creates a mock whenever an object ask for a Dependency. You can in fact write this test:

SNAGHTML1fd38a6

Figure 4: A test with AutoMockingContainer to resolve dependency with Mocks.

With this test, if you add more dependency in the constructor of BetterObjAnInterface, you does not suffer problems because each added dependency will be resolved with mocks automtically. With a little bit of helpers you can simplify more and write this test:

SNAGHTML2006ffb

Figure 5: A little helper to make using the AutomockingContainer trasparent to the test

This test is marked with the UseAutoMockingContainer helper, that accepts an array of types to register for the test. The test is now three lines long, one line to create the object, another one to exercise it, ant the final one to make an assertion on the ILogger mock that was automatically created by the AutoMockingContainer because BetterObjAnInterface declares a depencency on it.

Testing object designed with DI in mind is really easy Smile so get rid of your service locator Smile with tongue out

alk.

Mock, Service Locator, Automocking container and the hard life of testers

I know, service locator is an antipattern, but sometimes, when you begin to refactor existing code written with no IoC in mind, service locator can help you a little bit in restructuring your code. A service locator pattern work this way: you have some static or gloablly avaliable class named: ServiceLocator or IoC, and every object can query it for service implementation.

image

Figure 1: Simple schema of Service Locator Pattern, each object can query the SL asking for service

When you write unit test, this kind of pattern is really bad, suppose you want to write a test that exercise a class, and verifies that, upon certain condition, a log is generated into the system. If the Class Under Test is getting the logger with a call to Service Locator, we have a problem, because we need to find a way to make the service locator generates a mock, and give us back that mock to verify expectation on it.

If you have a well structured program, you should not use Service Locator, and your object should declare optional or required dependency with the usual technique of DI principle. In this scenario you do not have problem in using mocks or stub, because you can inject them from external code. To simplify both scenario the concept of AutoMockingContainer could help you. Basically an AutoMockingContainer is a IoC Container that work with these simple rules.

1) if the service is registered, resolve it and resolve all dependency with a specific MockStrategy

2) if the service is not registered, returns a mock.

3) make available to the caller all mocks that were created by the container, so the caller is able to issue expectation on them.

The basic tests for the container verify that resolving a registered object will resolve as usual, while when you ask for an unregistered object you got a mock.

[Test]

public void VerifyThatNotRegisteredComponentIsResolvedWithMock()

{

   using (AutoMockingContainer.AutoMockingContainer container = CreateAutoMockingContainer())

   {

       IAnInterface res = container.Resolve<IAnInterface>();

       res.Expect(t => t.DoTest()).Return(false);

       Assert.That(res.GetType().FullName, Is.StringContaining("Proxy"));

   }

}

 

[Test] 

public void VerifyThatImAbleToGetResolvedMockObjects()

{

   using (AutoMockingContainer.AutoMockingContainer container = CreateAutoMockingContainer())

   {

       IAnInterface res = container.Resolve<IAnInterface>();

       var retrieved = container.GetFirstCreatedMock<IAnInterface>();

       Assert.That(res, Is.EqualTo(retrieved));

   }

}

these simple two tests shows me that the AutoMockingContainer is able to resolve unregistered components as Mock Objects and this can helps me to solve the original problem: testing a class that internally uses the Service Locator to resolve something, like an ILogger. Suppose that this is the code of the class.

public class ObjAnInterface : IAnInterface

{

   #region IAnInterface Members

 

   public ObjAnInterface()

   {

       _logger = IoC.Resolve<ILogger>();

   }

 

   private ILogger _logger;

 

   public bool DoTest()

   {

       _logger.Debug("DoTestCalled");

       return true;

   }

 

   #endregion

}

The bad point is in the constructor, when the class asks to Service Locator for an ILogger. If we need to test this class and have a LOT of parts in the code where the class is created like this

var xxx = new ObjAnInterface()

it could be feasible to keep the service locator, and get rid of it during some later refactoring. I do not want to question on “it worth spending time to get rid of Service Locator?”, I want only to solve the scenario when you have no choice, the Service Locator is there and you cannot remove it.

In my test I want to be able to verify that the ILogger.Debug method is called when I call the DoTest() method of the class. First of all we need our AutoMockingContainer to be able to pass this test.

IAnInterface res1 = container.Resolve<IAnInterface>();

IAnInterface res2 = container.Resolve<IAnInterface>();

IAnInterface res3 = container.Resolve<IAnInterface>();

var retrieved = container.GetFirstCreatedMock<IAnInterface>();

Assert.That(res1, Is.EqualTo(retrieved));

var list = container.GetMock<IAnInterface>();

Assert.That(list, Is.EquivalentTo(new[] {res1, res2, res3}));

This simple test verifies that the container is able to resolve mocks, and the caller is able to get those mocks to setup expectation on them.

This is not enough, we need the Service Locator to declare an internal method that can be used to override the real Service Locator for testing purpose:

internal static IDisposable OverrideInstance< T > ( T instance )

{

    overrideInstances.Add ( typeof ( T ) , instance );

    return new DisposableAction ( () => overrideInstances.Remove ( typeof ( T ) ) );

}

Now it is possible for me writing code like this.

using (AutoMockingContainer.AutoMockingContainer container = SetupIoCWithAutomock())

{

    container.Register(Component.For<IAnInterface>()

        .ImplementedBy<ObjAnInterface>());

    IAnInterface res = container.Resolve<IAnInterface>();

    res.DoTest();

    var mock = container.GetFirstCreatedMock<ILogger>();

    mock.AssertWasCalled(m => m.Debug(Arg<string>.Is.Anything));

}

And the SetupIoCWithAutomock function is where the hard part takes place, it creates an AutoMockingContainer, and use the override method to instruct Service Locator to use that container until the test is end.

private AutoMockingContainer.AutoMockingContainer SetupIoCWithAutomock()

{

   IWindsorContainer windsorContainer = 

        new AutoMockingContainer.AutoMockingContainer();

   DisposeAtTheEndOfTest(IoC.OverrideEngine(new CastleIoC(windsorContainer)));

   return (AutoMockingContainer.AutoMockingContainer) windsorContainer;

}

This example shows one of the reason why Service Locator is bad, it makes your tests complex because you have to take care of all these greedy details. With some infrastructure class you can improve the test in this way.

Untitled

Figure 2: UseAutomockingCotnainer attribute permits you to automatically declare that this Test Fixture will use Automock in the Service Locator

In Figure 2 you can see that with a simple attribute I’m able to declare that for this TestFixture the global Service Locator class should be overridden with an AutoMockingContainer, then with a simple extension method (called AutoMockingContainer()) I’m able to get the container for that specific test and ask for Mock autogenerated by the container to setup expectation on them.

This makes the code more readable.

Alk.