seeing the light about abstractions

What a fantastic post this is: Limit your abstractions: And how do you handle testing?

I’m big enough to hold my hands up and say that I have often fallen foul of the needless abstraction.
To some extent, I did realise this when redesigning my site to work with fubuMVC –previously I had encapsulated logic in something I called controller messaging for some time (and had planned to blog about but never got around to it).

The original version was in an ASP.NET MVC controller and was used in a similar vein to domain events:

    public class ReportController : AuthorisedController
    {
        public ActionResult Create(int id)
        {
            var reportTreeData = ControllerMessage.Initiate<NewReportToBeCreated, ReportTreeData>
                (new NewReportToBeCreated() {ReportTemplateId = 1, PupilId = id});

            return View(reportTreeData);
        }
    }

When I came to do my fubuMVC implementation I thought there was a code smell about having almost exactly the same construct as domain events, but for controllers to hook into domain logic.
So instead I wanted it baked into the actions on fubuMVC - the actions/controllers in my fubuMVC application derive from a base that has an invoker:

    public class ControllerThatCanInvoke
    {
        public static ControllerMessageInvoker Invoker { get; set; }

        protected TResult Invoke<T, TResult>(T item)
        {
            return Invoker.Invoke<T, TResult>(item);
        }
    }

It has a static invoker that is set up at the bootstrapping stage and the invoke call is delegated to the invoker.

The invoker comes from the IOC container and this is injected with handlers:

    public class ControllerMessageInvoker
    {
        readonly IEnumerable<IHandle> _handlers;

        public ControllerMessageInvoker(IEnumerable<IHandle> handlers)
        {
            _handlers = handlers;
        }

        public TResult Invoke<T, TResult>(T item)
        {
            return _handlers.OfType<IHandle<T, TResult>>().Single().Handle(item);
        }
    }

With the handler interfaces:

    public interface IHandle<T, TResult> : IHandle
    {
        TResult Handle<T>(T item);
    }

    public interface IHandle { }

So this enables me to invoke straight from my controller :

    public class ReportController : ControllerThatCanInvoke
    {
        public CreateReportViewModel Create(CreateReportInput input)
        {
            var reportTreeData =
                Invoke<NewReportToBeCreated, ReportTreeData>(new NewReportToBeCreated
                                                                 {
                                                                     ABC = input.MMM,
                                                                     XYZ = input.Id
                                                                 });

            return new CreateReportViewModel(reportTreeData);
        }
    }

This allows me to test that the controller initiates the invocation and with the right inputs on a POCO class and I can test the handler independently.
What that obviously means is I need a handler that answers to the invocation:

    public class NewReportToBeCreatedHandler : IHandle<NewReportToBeCreated, ReportTreeData>
    {
        public ReportTreeData Handle<T>(T item)
        {
            DoSomething();
            return xxxx;
        }
    }

This works well, I have separation of concerns, this handler comes from the IOC container and can have session and other dependencies injected, and I've been rolling along very happy with myself until I read the blog post I referred to.

It poses a question: Do I really need this IHandler<T,TResult> abstraction?

The only friction I have at the moment is that I need two POCO classes and a handler class for every action that requires this invocation style. It ends up being a lot of classes.
I’ve managed it so far with some good folder and namespace arrangement, but I now see the light:

I do not need this abstraction and its trappings at all.

It is a concept I carried over from an ASP.NET MVC implementation and I just don’t need it.
So I’m in the process of reworking / stealing the ideas from Oren’s post and I’ll put up how I’ve reconsidered this for fubuMVC in my next post.

Posted at at 6:51 PM on Monday, February 27, 2012 by Posted by Justin Davies | 0 comments Links to this post   | Filed under: ,

How I use domain events with fubuMVC part two

In my previous post I illustrated how I use domain events and enable a pre-commit  and post-commit behaviour on one handler interface.
Here I’m going to illustrate how to plug this into the fubuMVC framework.

In another previous post I showed how an NHibernate simple unit of work can be used in fubuMVC with a dedicated behaviour and now I want to extend that behaviour so that is processes the post-commit actions. Here’s the invoke method of that behaviour:

        public void Invoke()
        {
            _fubuRequest.Set(new Lazy<ISession>(() => _session ?? 
                   (_session = CreateTransactionalSession())));

            try
            {
                InnerBehavior.Invoke();

                if (_session != null)
                    _session.Transaction.Commit();
            }
            catch (Exception)
            {
                if (_session != null)
                    _session.Transaction.Rollback();
                throw;
            }
            finally
            {
                if (_session != null)
                    _session.Dispose();
            }

            ProcessAfterEventConfirmationActions();
        }

This is the existing Invoke code with an extra method added on at the end to process these "after event confirmation" actions. Here's the implementation of that:

        void ProcessAfterEventConfirmationActions()
        {
            var actions = _fubuRequest.Get<List<AfterEventConfirmationAction>>();
            if (actions == null)
                return;

            actions.ForEach(action => action());
        }

Pretty simple stuff - it cycles through the list of after event confirmation actions that it has obtained from the current fubu request. If isolated error handling is required, it should be contained within the action itself.

The next step is to plug this into the domain events processor, but I have a problem. My domain event processor that I showed in my last post is obtained from the static provider delegate:

    public static class DomainEvents
    {
        static Func<IProcessDomainEvents> _domainEventProcessorProvider;

        public static void SetDomainEventProcessorProvider(Func<IProcessDomainEvents> 
                     domainEventProcessorProvider)
        {
            _domainEventProcessorProvider = domainEventProcessorProvider;
        }

        public static void Raise<TEvent>(TEvent domainEvent) where TEvent : IDomainEvent
        {
            var domainEventProcessor = _domainEventProcessorProvider();
            domainEventProcessor.ProcessEvent(domainEvent);
        }
    }

...and this is declared at the bottom of my HttpApplication :

public class Global : HttpApplication
    {
        Container _applicationsContainer;
        IProcessDomainEvents _domainEventsProcessor;

        protected void Application_Start(object sender, EventArgs e)
        {
            FubuApplication
                .For<XercesFubuRegistry>()
                .StructureMap(() =>
                {
                    var container = new Container(new ContainerConfigurer().Configuration);
                    _applicationsContainer = container;
                    return container;
                })
                .Bootstrap(RouteTable.Routes);

            DomainEvents.SetDomainEventProcessorProvider(DomainEventsProcessor);
        }

        private IProcessDomainEvents DomainEventsProcessor()
        {
            return _domainEventsProcessor ??
                    (_domainEventsProcessor = _applicationsContainer.GetInstance<IProcessDomainEvents>());
        }
    }

Because the processor is obtained from the root container, any fubu request it receives will not be the one from the nested container of the current request.
I therefore need to build myself a simple bridge between the two:

    public interface IFubuRequestBridge
    {
        void StoreRequest(IFubuRequest fubuRequest);

        IFubuRequest ObtainRequest();
    }

    public class FubuRequestBridge : IFubuRequestBridge
    {
        public const string FubuRequestKey = "XERCES_FUBUREQUEST";

        public void StoreRequest(IFubuRequest fubuRequest)
        {
            HttpContext.Current.Items[FubuRequestKey] = fubuRequest;
        }

        public IFubuRequest ObtainRequest()
        {
            return HttpContext.Current.Items[FubuRequestKey] as IFubuRequest;
        }
    }

This fubu request bridge can store and provide the current request and simply places it in the current http context.

The storing of the request is performed using a behaviour dedicated to doing only that:

    public class DomainEventsBehaviour : BasicBehavior
    {
        readonly IFubuRequest _fubuRequest;
        readonly IFubuRequestBridge _fubuRequestBridge;

        public DomainEventsBehaviour(IFubuRequest fubuRequest, IFubuRequestBridge fubuRequestBridge) 
                            : base(PartialBehavior.Ignored)
        {
            _fubuRequest = fubuRequest;
            _fubuRequestBridge = fubuRequestBridge;
        }

        protected override DoNext performInvoke()
        {
            _fubuRequestBridge.StoreRequest(_fubuRequest);

            return DoNext.Continue;
        }
    }

Injected with the current fubu request and the bridge, it stores the fuburequest before invoking the next behaviour.
I put this in the fubu registry before the simple unit of work one:

            ApplyConvention<PermanentRedirectionConvention>();
            ApplyConvention<WrapAllConvention<DomainEventsBehaviour>>();
            ApplyConvention<WrapAllConvention<SimpleUnitOfWorkBehaviour>>();
            ApplyConvention<AuthenticationConvention>();

So now I can change my domain event processor to be injected with the bridge – to store the post event confirmation actions it simply retrieves the appropriate fubu request and places them in a list:

    public class DomainEventProcessor : IProcessDomainEvents
    {
        readonly IEnumerable<IHandleDomainEvents> _domainEventHandlers;
        readonly IFubuRequestBridge _fubuRequestBridge;

        public DomainEventProcessor(IEnumerable<IHandleDomainEvents> domainEventHandlers, 
                                               IFubuRequestBridge fubuRequestBridge)
        {
            _domainEventHandlers = domainEventHandlers;
            _fubuRequestBridge = fubuRequestBridge;
        }

        public void ProcessEvent<T>(T domainEvent) where T : IDomainEvent
        {
            _domainEventHandlers.OfType<IHandleDomainEvent<T>>()
                                .ForEach(handler => HandleTheDomainEvent(domainEvent, handler));
        }

        void HandleTheDomainEvent<T>(T domainEvent, IHandleDomainEvent<T> handler) 
                  where T : IDomainEvent
        {
            var afterEventConfirmationAction = handler.Handle(domainEvent);

            var fubuRequest = _fubuRequestBridge.ObtainRequest();

            var currentAfterEventConfirmationActions = 
               fubuRequest.Get<List<AfterEventConfirmationAction>>();
            currentAfterEventConfirmationActions.Add(afterEventConfirmationAction);
        }
    }

And that’s it!
A lot of code in this post, but essentially a working domain events implementation in fubuMVC that does processing within a transaction and post confirmation actions after the committal.

Posted at at 8:46 AM on Friday, February 24, 2012 by Posted by Justin Davies | 0 comments Links to this post   | Filed under: ,

How I use domain events with fubuMVC–part one

My fubuMVC series is back and with an interesting one hopefully – how I use domain events and work it into my fubuMVC application.
To illustrate this I’m going to use the registration process as a prime example of domain events in action within an application.

When a user registers, I want to create a new user who is persisted to the database and a confirmation email sent to the user.
Using domain events for this I want the UserCreated event to signal that the user needs persisting so that this is loosely coupled but I only want the email sent if the entire previous transaction was successful.

So I’m going to start with an event that has an empty marker interface IDomainEvent:

    public class UserCreated : IDomainEvent
    {
        public UserCreated(User user)
        {
            User = user;
        }

        public User User { get; private set; }
    }

In order to handle this event, I’m going to create a domain event handler abstraction:

    public interface IHandleDomainEvents { }

    public interface IHandleDomainEvent<T> : IHandleDomainEvents
    {
        AfterEventConfirmationAction Handle(T domainEvent);
    }

    public delegate void AfterEventConfirmationAction();

This interface can handle a domain event T and has the option of returning an action that will happen once the event has been confirmed (i.e. transaction is complete).
I chose a strong delegate as opposed to Action so that is has a recognisable name throughout the code. Here are two pseudo implementations from the registration example:

    public class PersistTheCreatedUserHandler : IHandleDomainEvent<UserCreated>
    {
        public AfterEventConfirmationAction Handle(UserCreated domainEvent)
        {
            // persist the user
            session.Save(user);

            return Do.Nothing();
        }
    }

    public class EmailForTheCreatedUserHandler : IHandleDomainEvent<UserCreated>
    {
        public AfterEventConfirmationAction Handle(UserCreated domainEvent)
        {
            return () => SendEmail();
        }
    }

The difference between the two is that the persistence will happen within a transaction, yet the send email will occur only once all events have been confirmed.

Now onto the domain events processor – I want it injected with all the available handlers so that it can cycle through the appropriate ones and ask them to handle the event:

    public class DomainEventProcessor : IProcessDomainEvents
    {
        readonly IEnumerable<IHandleDomainEvents> _domainEventHandlers;
        readonly List<AfterEventConfirmationAction> _temporaryHolderForAfterEventConfirmationActions = 
                                                              new List<AfterEventConfirmationAction>();

        public DomainEventProcessor(IEnumerable<IHandleDomainEvents> domainEventHandlers)
        {
            _domainEventHandlers = domainEventHandlers;
        }

        public void ProcessEvent<T>(T domainEvent) where T : IDomainEvent
        {
            _domainEventHandlers.OfType<IHandleDomainEvent<T>>()
                                .ForEach(handler => HandleTheDomainEvent(domainEvent, handler));
        }

        void HandleTheDomainEvent<T>(T domainEvent, IHandleDomainEvent<T> handler) where T : IDomainEvent
        {
            var afterEventConfirmationAction = handler.Handle(domainEvent);

            _temporaryHolderForAfterEventConfirmationActions.Add(afterEventConfirmationAction);
        }
    }

The processor ensures the domain events get handled and I don't have error handling to ensure all are fired, I personally let the error roll up and fail the entire transaction.
Temporarily I’m storing the event confirmation actions and doing nothing with them – the next post will illustrate how I hook this into fubuMVC.

The final piece is an easy way for domain objects to raise events:

    public static class DomainEvents
    {
        static Func<IProcessDomainEvents> _domainEventProcessorProvider;

        public static void SetDomainEventProcessorProvider(Func<IProcessDomainEvents> 
                                 domainEventProcessorProvider)
        {
            _domainEventProcessorProvider = domainEventProcessorProvider;
        }

        public static void Raise<TEvent>(TEvent domainEvent) where TEvent : IDomainEvent
        {
            var domainEventProcessor = _domainEventProcessorProvider();
            domainEventProcessor.ProcessEvent(domainEvent);
        }
    }

I do not like implementations in my static classes and methods, rather they delegate out as this one does using a static provider/factory to obtain the processor to use. Here's an example of this static in use:

        DomainEvents.Raise(new UserCreated(user));

In the next part I’ll show how these get hooked into the fubuMVC request and interact with my unit of work behaviour.

Posted at at 6:49 AM on Wednesday, February 22, 2012 by Posted by Justin Davies | 0 comments Links to this post   | Filed under: ,

on behavioural testing

I’m back after a long spell away from blogging, having settled into a new work position and having had a few personal code retreats I recently talked about.

In that time I wanted to explore what it means to unit test and acceptance test and came to a few conclusions that I wanted to share.

Test driven development

Years back when I first started test driven development it was a revelation – the control it gave you over your own code, the confidence in what you were delivering was amazing. I started with stubs, test spies and all kinds of funky hand rolled stuff, but soon found that mocking frameworks enabled you to gain stubs for free using their proxies. This is when the testing began to naturally morph into interaction testing – by testing the relationships between single responsibility objects I had full control over my code and could edge case everything.

This is where I think a lot of people get to, having read debates about state vs. behavioural testing and a few blogs where great developers admit that “I made a mistake and got too involved in interaction testing”.
Some of us who have been through this recognise the brittle unit tests that come with behavioural unit testing, however it is not black and white that this brittleness is a bad thing.

I specialise in helping teams become more agile and teach test driven development, and more often than not the environment that I enter is one where unit testing gets done, but test driven does not. And there are only 150 tests on a huge code base.
I find that a natural fit for the developers who want to get started on TDD with this code base, which is often huge classes with mangled responsibilities and little dependency injection, is to go with the tried and tested way of pulling out single responsibility behaviour using a test driven practice and moving the code out piece by piece, introducing dependency injection and abstractions where appropriate.
This then naturally encourages behavioural interaction using mocking frameworks for stubs because they want to ensure that these new SRP pieces speak to each other in the right way and that less TDD thinking developers don’t rip it out.
They embrace potentially brittle tests with the knowledge that they might need changing or reworking in the future in exchange for a higher level of confidence that the behaviour of our code is correct. More importantly their code base becomes testable.
Provided this is a conscious decision, I think it can have great benefits.

Acceptance test development

In an ideal world, we would start a clean project with acceptance testing up front, or rather Specifications By Example. By driving features that examine how and what the product owner/customer sees in our application we can free ourselves up from a lot of the internal behavioural testing. We potentially then unit test where there is complexity or edge cases and let the acceptance tests cover the rest when we want to.

I’m working on a project at the moment that falls somewhere between the two – there are unit tests, we are introducing dependency injection and splitting responsibilities, yet we already recognise the value of acceptance tests. More importantly, this end to end feature testing is very possible with some internal changes to the code and some abstractions. These higher level tests will free us from the test per class restraint we often find ourselves in while test driving a legacy code base.

To conclude I think that test per class and behavioural testing is not a bad thing at all, just that if you can there are better ways to reduce brittleness and test rework.

Posted at at 7:53 AM on Thursday, February 16, 2012 by Posted by Justin Davies | 0 comments Links to this post   | Filed under: ,