Composition vs derivation

Assume you’re writing some reports in your application. You’ve just created the third controller covering some kind of reporting and it seems to be, that all the three controllers have a very similar code, modulo type passed as the entity type to your NH ISession.QueryOver() or another data source. It seems that, if the method creating report base was generic, it could be used in all the cases. You want to extract it, make it clearer and to stop repeating yourself. What would you do?

Derivation
The very first thing is to extract method in each of the controllers. Now they seem almost the same. A place is needed where the method can be easily moved. How about a super type? Let’s create a controller, call it in a fashionable way, for instance: ReportControllerBase, and move the method in there. Now you can easily remove the methods in the deriving controllers. Yeah! It’s reusable, everyone writing his/her report can derive from the ReportControllerBase and use its methods to speed up his/her task.

Composition
The very first step is exactly the same: the extract method must be done, to see the common code. Once it’s done, you notice that the whole method has only a few dependencies which can be easily pushed to parameters, for instance: isession, the entity type passed to query, the value used in some complex where clause, etc. You change all the field and properties usages to parameters which allows this method to be static. You create a static method and turn it into an extension method of a session. The refactorization is done, you can easily call this method in all the controllers, by simply calling an extension onto a session.

What’s the difference and why composition should be preferred
If you use C# or Java you should always be aware of one limitation: you can derive from only one type. Spending this ‘once in a lifetime’ for a simple functionality extraction, for me – that’s the wrong way. Using composition, and deriving only when you truly see that one type is another type, that’s the right way to go. In the next post I’ll write about ASP MVC Detached Actions, a simple mechanism you can use, to derive your controllers only, when it is needed and delegating common actions, without it.

Simplicity of your architecture

A few days ago I watched a nice presentation published by Infoq called Simplicity Architect which made me think one more about design decisions I’ve been making through the last one year. Dan North, which was the speaker remind of the major problem every architect, I’d say, designer has. The problem is complexity lurking in the dark corners of each solution. I can remember times when from-zero-to-working-example took my team more than one month because of the db creation, design, and other stuff which you can qualify as things, which your business don’t understand. During the very last startup, it took me only 2 hours to provide the very basic set of functionalities with viewing and filtering a list of entities, editing them and so on. I did use a few tools (NHibernate, log4net, Unity and my infrastructure part injecting it all in MVC in my way), but it was only 2 hours to have a working example and it was _simple_ in terms of design. I did like it as the business owner did.

Hope you don’t get too complex either.

Project structure

I’ve been working on a few quite big projects recently. The first I was dropped into was designed a few months before my arrival and had the solution consisting of almost 60 projects. The references were cascading, with each project having all the previous referenced. The web project depended on all of the projects, and had nothing in common with terms like dependency injection, ORM, best practices. All the data access code was written with using SqlCommands with caching thrown in multiple places. The same with other blocks you can imagine such as validation, logging, gathering statistics, etc. Reviewing the code made me think about NIH syndrome.

The second project was designed to handle a lot of stuff, for instance lifetime management (a very special case) and  very domain specific workflows. The design was done in 80% when I entered the project. We tried to write not much code, using already provided frameworks for different purposes like: NHibernate, log4net, NServiceBus, Irony parser (for domain specific language). Then the first version was established, the solution had 16 projects. Two weeks ago I made a major refactorization, reducing a few service and code-based (yet another abstraction) boundaries, creating a more integrated, yet _not_more_ coupled system. The final solution was performing better and had much simpler deployment. It consisted of 11 projects.

The very last solution consisted of 6 projects:

  • Web (having reference to NHibernate and Model)
  • Web.Config (infrastructure stuff, all the DI registrations, referencing all libraries and setting up controller factory in ControllerBuilder and default ModelBinder, infrastructure service implementations)
  • Model (entities, factories, services, types – like email, domain events and their handlers)
  • Model.Impl (implementation of interfaces from Model split in the Model’s manner)
  • Model.Persistence (all the NH event listeners, Fluent NH mappings, Solr services)
  • Model.Presentation (simple denormalized readonly objects to be used for queries result, possibly with Solr)

Do my solutions become to minimal? As far as the last solution is being built it does not seem so. The responsibilities are clean and all can be easily put into this separation. How do you find it? Any ideas?

Domain events with Unity Container extension

I do like domain events perfectly described by Udi. I’d like to share my implementation of this pattern, using Unity (my preferable container), which seems to be simple, short and still powerful. I assume, that you read the Udi’s article carefully. First and foremost: the domain interfaces

    /// <summary>
    /// The markup interface for any system event.
    /// </summary>
    public interface IEvent
    {
    }

    /// <summary>
    /// The interface of a handler for events of type <typeparamref name="T"/>.
    /// </summary>
    /// <typeparam name="T">The type of the event to handle.</typeparam>
    public interface IEventHandler
        where T : IEvent
    {
        /// <summary>
        /// Handles the specified @event.
        /// </summary>
        /// <param name="event">The @event.</param>
        void Handle(T @event);
    }

    /// <summary>
    /// The interface of event manager, allowing raising events based on the <see cref="IEvent"/>.
    /// </summary>
    public interface IEventManager
    {
        /// <summary>
        /// Raises the specified event, not requiring, 
        /// that it is handled by any handler.
        /// </summary>
        /// <typeparam name="T">The type of the event.</typeparam>
        /// <param name="event">The @event.</param>
        /// <remarks>
        /// The method iterates through all of the registered handlers for the event of type <typeparamref name="T"/>.
        /// </remarks>
        void Raise(T @event)
            where T : IEvent;
    }

I assume usage of dependency injection and having the IEventManager implementation injected. Speaking about the IEventManager implementation it’s fairly simple, located in a project knowing the Unity assembly (Infrastructure in my case). It’s worth to mention, that I consider handlers to be transient objects, constructed and discarded immediately after event handling.

    /// <summary>
    /// The implementation of event manager using the container to resolve handlers.
    /// </summary>
    public class EventManager : IEventManager
    {
        private readonly IUnityContainer _container;

        [DebuggerStepThrough]
        public EventManager(IUnityContainer container)
        {
            _container = container;
        }

        [DebuggerStepThrough]
        public void Raise(T @event)
            where T : IEvent
        {
            var handlers = _container.&lt;ResolveAll&gt;();

            foreach (var handler in handlers)
            {
                try
                {
                    handler.Handle(@event);
                }
                finally
                {
                    _container.Teardown(handler);
                }
            }
        }
    }

The last but not least: how to register all the handlers in the container? I wrote a small unity extension providing assembly scan functionality which can be found below. The are two mouthful method names in the code:

  • GetFirstClosedGenericInterfaceBasedOnOpenGenericInterface, which tries to do what is written it does :P
  • RegisterInstanceWithSingletonLifetimeManager,an extension methods using a I-have-nothing-to-do-with-monitors LifetimeManager for setting up the singletons

The code itself:

    /// <summary>
    /// The <see cref="UnityContainer"/> extension registering all the event handlers
    /// and unity-based implementation of <see cref="IEventManager"/>.
    /// </summary>
    /// <remarks>
    /// The event handlers are regsitered as classes with transient lifetime. 
    /// Their instances are tear down immediately after usage.
    /// </remarks>
    public class EventUnityContainerExtension : UnityContainerExtension
    {
        protected override void Initialize()
        {
            var eventManager = new EventManager(Container);
            Container.RegisterInstanceWithSingletonLifetimeManager(eventManager);
        }
        /// <summary>
        /// Registers all the event handlers from assembly of the passed type <typeparamref name="T"/>.
        /// </summary>
        /// <typeparam name="T">The type which assembly should be scanned.</typeparam>
        /// <returns>This instance.</returns>
        public EventUnityContainerExtension RegisterHandlersFromAssemblyOf<T>()
        {
            return RegisterHandlersFromAssembly(typeof(T).Assembly);
        }

        /// <summary>
        /// Registers all the event handlers from all <paramref name="eventHandlersAssemblies"/>.
        /// </summary>
        /// <param name="eventHandlersAssemblies">List of assemblies to scan.</param>
        /// <returns>This instance.</returns>
        public EventUnityContainerExtension RegisterHandlersFromAssemblies(params Assembly[] eventHandlersAssemblies)
        {
            foreach (var eventHandlersAssembly in eventHandlersAssemblies)
            {
                RegisterHandlersFromAssembly(eventHandlersAssembly);
            }

            return this;
        }

        private EventUnityContainerExtension RegisterHandlersFromAssembly(Assembly assembly)
        {
            foreach (var type in assembly.GetTypes())
            {
                if (type.IsInterface || type.IsAbstract)
                {
                    continue;
                }

                var handlerInterface = type.GetFirstClosedGenericInterfaceBasedOnOpenGenericInterface(typeof(IEventHandler));
                if (handlerInterface == null)
                {
                    continue;
                }

                // the type is registered with a name, because only named registrations can be resolved by unity.ResolveAll method
                Container.RegisterType(handlerInterface, type, type.FullName, new TransientLifetimeManager());
            }

            return this;
        }
    }
}

Simple and powerful, isn’t it? :)

NServiceBus callback failure

Today I found a bug in NServiceBus, which occured just before publishing our project. I isolated the bug, and published the unit test on the SourceForge, but I’m not quite sure whether the project is still alive (there are a few tickets untouched). The link to the isolated case: http://sourceforge.net/tracker/?func=detail&atid=1009068&aid=3092090&group_id=209277

The problem is a race condition which can occur when the service using Reply, replies before the callback is registered to the message. The scenario is simple: the reply message correlation id is not found in the dictionary and the message is consumed with no trace left. The callback registration occurs after this and hence, it will never be fired at all. Sad but true: this eliminates NServiceBus’ synchronous way to go.

It seems that for now, I cannot use callbacks at all (replying with messages handled by handlers works perfectly since it does not use this ‘correlation stuff’). Worth to notice, that I’ve got to redo a lot of work because of this ‘feature’.

Any thoughts about that?

I demand configuration

In the previous posts I described the intentions behind Themis. It’s time do deepen into demand and the whole configuration. Imagine a domain of car drivers. It includes car drivers as well as driven cars. The simplest demand which one can come up with is a simple check, whether one can drive a specific car.

public class CanDrive : IDemand<bool>
{
    public CanDrive(Car car)
    {
        Car = car;
    }

    public Car Car { get; private set; }
}

Speaking about a car and car driver:

public class DriverRole
{
    public DriverRole(int skillLevel)
    {
        SkillLevel = skillLevel;
    }

    public int SkillLevel { get; private set; }
}

public class Car
{
    public Car(int requiredSkillLevel)
    {
        RequiredSkillLevel = requiredSkillLevel;
    }

    public int RequiredSkillLevel { get; private set; }
}

The last but one thing, which should be done is to create a defintion of the DriverRole. By creating a definition I mean, creating a set of rules applied to evaluated demands in scope of the role context:

public class DriverRoleDefinition : RoleDefinition<DriverRole>
{
    public DriverRoleDefinition( )
    {
        Add<CanDrive, bool>((d, r) => d.Car.RequiredSkillLevel <= r.SkillLevel);
    }
}

Having all of this, during application startup one can easily configure the demand service with fluent configuration:

var demandService = Fluently.Configure()
    .AddRoleDefinition(new DriverRoleDefinition())
    .BuildDemandService();

and use the created service to evaluate demand canDrive created on a retrieved car basis, passing the driver role as the argument

return _demandService.Evaluate<CanDrive, bool>(canDrive,  driverRole).Any(b=>b);

In the solution, I created a more meaningful example (Themis.Example project), showing how with simple extension methods get rid of plenty of generic parameters.

In the next posts I’ll write about Themis extension points and describe a way in which I want to integrate it with NHibernate.

I demand IDemand

The main interface of Themis is IDemand.

public interface IDemand
{
}

An example implementations:

public class EntityPermission : IDemand
{
    public EntityPermission(TEntity entity)
    {
        Entity = entity;
    }

    public TEntity Entity { get; private set; }
}

public class View : EntityPermission
{
    public View(TEntity entity)
        : base(entity)
    {
    }
}

A simple interface, with no members at all. The class implementing it defines the demand name as well as the result which should be provided by the system evaluating the demand. Implementations of IDemand should be contextful, passing all the needed context for the demand evaluation in their properties. The TResult can be any type, but in majority of authorization cases it’ll be nothing more then bool. We want a yes/no answer for ‘Can I?’ question, don’t we? :)

Having the defined roles and demands we can move to the UI and write a simple authorization check. Being given an instance of IDemandService (by constructor injection), I can write in my ASP MVC controller a simple check of a demand/authorization. Below you can find the signature of IDemandService, a simple extension method written to ease using the service in a specific domain (a wrapping service is also a good solution) and the usage example itself.

public interface IDemandService
{
    IEnumerable<TResult> Evaluate<TDemand, TResult>(TDemand permission, params object[] roles)
        where TDemand : IDemand<TResult>;
}

Useful extension methods written in the app using Themis. The names, I hope, are self-descriptive.

    public static class AuthorizationServiceExtensionMethods
    {
        public static bool Can<TDemand>(this IDemandService demandService, TDemand permission, 
            params object[] roles)
            where TDemand : IDemand<bool>
        {
            return demandService
                .Evaluate<TDemand, bool>(permission, roles)
                .Any(b => b);
        }

        public static bool CanEdit<TEntity>(this IDemandService demandService, TEntity entity, 
            params object[] roles)
        {
            return demandService
                .Evaluate<Edit<TEntity>, bool>(new Edit<TEntity>(entity), roles)
                .Any(b => b);
        }

        public static bool CanView<TEntity>(this IDemandService demandService, TEntity entity, 
            params object[] roles)
        {
            return demandService
                .Evaluate<View<TEntity>, bool>(new View<TEntity>(entity), roles)
                .Any(b => b);
        }
    }

And finally, the app code example in which you can see that role management was delegated to an enigmatic IRoleService. The ‘Should I use NH session to manage roles?’ question is out of scope of this entry.

public ActionResult View(Guid id)
{
    var car = _session.Get<Car>(id);
    var roles = _roleService.GetCurrentUserRoles();
    if (!_demandService.CanView(car, roles))
        throw new InvalidOperationException("You cannot view this car!");

    return View(car);
}

Isn’t is simple? What about the expressions and the configuration? I’ll cover it soon.