Javascript basics Part 1: By convention

Standard

Usually when doing javascript, you’ll see a lot of script inside a page. For instance when we add a datapicker on a text input, you could add a script block to the page and do the necessary initialization there

Now what if we needed to do this more then just once? Let’s change our html to a more unobtrusive way:

Now just add a new javascript file to your website and include it in our html.

In this file we make sure we alias ‘$’ to jQuery as another plugin we use could have aliased it differently.

REMARK: If you are worried about performance of the selector used here, you can always use a class in your convention

Who manages the transaction?

Standard

In my last post we talked about letting our container manage our ISession lifetime. Immediatly after publishing this post, i’ve got a lot of reactions considering the management of transactions, more specificly about issueing a rollback when an exception has been thrown.

A simplistic approach would be to do this in every commandhandler:

But this approach seems rather cumbersome and not very flexible. What if we could automate this repeated code pattern more or less like what behaviors are doing in a WCF context ? We need some sort of AOP approach.

Meet AutoTx interceptor

Basicly this code takes the entire transaction idiom from our hands, it starts a transaction if not allready started and if the interceptor started the transaction it will commit or rollback (depending on exceptions thrown) the transaction.

The registration

Nothing really special going on, just not forget to opt-in for Lazy resolving and register the interceptor as transient, so that it’s lifetime gets bound to whom it is intercepting.

Use your container to manage Session lifetime

Standard

There are many blog posts on how to manage the lifetime of ISession in a web application. Mainly because only ISessionFactory is thread-safe, which is a good thing because your ISession instance acts as a unit of work. For a web application the advised solution is to use the session-per-request pattern.

Even myself created one in the golden years, I’ve even posted it SourceForge a decade ago, but I’ve seem to have lost the link over the years. Coincidence, maybe ;)

Well as I tend to include a container in my projects, why not let your container manage this for you? It knows about lifetime/lifestyle’s, so why reinventing the wheel again?

NHibernateConfigurationBuilder

First we create a builder around the Configuration class, because i personally hate to put everything in an Xml file and I don’t believe my database of choice is going to change in the middle of my project. This is not a needed step, but it includes some goodies

using NHibernate.Cfg;
using NHibernate.Dialect;
using NHibernate.Driver;
using NHibernate.Mapping.ByCode;
using NHibernate.Tool.hbm2ddl;

namespace Nebula.Data
{
    public class NHibernateConfigurationBuilder
    {
        private string connectionStringName;

        public NHibernateConfigurationBuilder()
        {
            connectionStringName = "Nebula";
        }

        public NHibernateConfigurationBuilder UsingNamedConnectionString(string connectionStringName)
        {
            this.connectionStringName = connectionStringName;
            return this;
        }

        public Configuration Build()
        {
            var configuration = new Configuration();

            // initialize database configuration
            configuration.DataBaseIntegration(cfg =>
            {
                cfg.ConnectionStringName = connectionStringName;
                cfg.Driver<Sql2008ClientDriver>();
                cfg.Dialect<MsSql2008Dialect>();
                cfg.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
            });

            // initialize mappers
            var mapper = new ModelMapper();
            mapper.AddMappings(GetType().Assembly.GetExportedTypes());
            configuration.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

            // Auto Quote all table and column names
            SchemaMetadataUpdater.QuoteTableAndColumns(configuration);

            return configuration;
        }
    }
}

The Installer

Wrap all registrations up in an installer and inject session anywhere you want

using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;
using NHibernate;
using Nebula.Data;

namespace Nebula.Bootstrapper.Installers
{
    public class NHibernateInstaller : IWindsorInstaller
    {
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            ISessionFactory sessionfactory = new NHibernateConfigurationBuilder()
                .Build()
                .BuildSessionFactory();

            container.Register(
                Component
                    .For<ISessionFactory>()
                    .Instance(sessionfactory));

            container.Register(
                Component
                    .For<ISession>()
                    .UsingFactory<ISessionFactory, ISession>(factory => factory.OpenSession())
                    .LifestylePerWebRequest());
        }
    }
}

For the registration of ISessionFactory i could have used a factory method, but that would delay any possible configuration mismatches until the first time a sessionfactory/session is needed.

If you have a usecase for IStatelessSession, append this to the installer and you are good to go:

container.Register(
    Component.For<IStatelessSession>()
             .UsingFactory<ISessionFactory, IStatelessSession>(factory => factory.OpenStatelessSession())
             .LifestylePerWebRequest());
    };

Side note

The same mechanics can also be used to manage the lifetime of Entity framework’s objectcontext! Even if you are in a wcf context, just change the lifestyle of your session accordingly (ehum wcf facility) ;)

I let you know that something happened

Standard

How do you handle follow-up actions of important things that happened in your code? For instance when a new user registered on your site you need to send him a registration verification link. Are you just adding the necessary pieces of code into your existing code block? What happens if you need to also send an email to the administrator of the website, so he may already setup the necessary roles for the newly registered user? Or you need to automatically create a backorder when stock of a specific product runs out?

The event

An event is the acknowledgement that something important did happen in your system. The name always indicates that something did happen, so it is always in past tense.

public interface IEvent { }

Possible example

public class AccountRegistered : IEvent
{
   public string Email { get;set; }
}

The event subscriber/handler

An event subscriber subscribes to a specific event, its execution happens synchronously. Important thing to notice here is that there can be multiple subscribers to the same event, they will be run in any order. Normally they will happen into the same Context/UnitOfwork/Transaction as the event originator. But it is also possible to queue a new message on a MSMQ/Bus in a subscriber.

public interface ISubscribe<T>
{
    void On(T @event);
}

Possible example

public class SendVerificationMailOnAccountRegistered : ISubscribe<AccountRegistered> 
{
   	public void On(AccountRegistered @event)
	{
		// Send email to registered user with email
	}
}

Easy access

Now i personally prefer raising these events from where it belongs, more specific in the domain code. Now how could we raise events in an easy way and automatically execute all the needed subscribers? I avoid doing any form of Dependency Injection in my domain, we’ll need some static gateway to something that dispatches the events

public static class DomainEvents
{
    private static volatile IEventDispatcher _dispatcher = new NullEventDispatcher();
    private static readonly object Syncroot = new object();

    public static IEventDispatcher Dispatcher
    {
        get { return _dispatcher; }
        set
        {
            lock (Syncroot)
                _dispatcher = value ?? new NullEventDispatcher();
        }
    }

    public static void Raise<T>(T @event) where T : IEvent
    {
        Dispatcher.Dispatch(@event);
    }
}

This allows me to do the following in my domain code:

DomainEvents.Raise(new AccountRegistered { Email="someone@google.com" });

IEventDispatcher

Let’s take a closer look at the event dispatcher contract and 3 example implementations

The contract

public interface IEventDispatcher
{
    void Dispatch<T>(T @event) where T : IEvent;
}

NullEventDispatcher

As i hate those pesky NullReferenceExceptions, i made myself a default null object implementation. It has the responsibility to do exactly nothing ;)

public class NullEventDispatcher : IEventDispatcher
{
    public void Dispatch<T>(T @event) where T : IEvent
    {
    }
}

Collecting Events for unit test purposes

This implementation can be used to unit test if a specific event has occurred, although one could also use mocked one.

public class CollectingEventDispatcher : IEventDispatcher, IEnumerable<IEvent>
{
	[ThreadStatic] private static Queue<IEvent> _occurredEvents;

    private static Queue<IEvent> OccurredEvents
    {
        get { return _occurredEvents ?? (_occurredEvents = new Queue<IEvent>()); }
    }

    public IEnumerator<IEvent> GetEnumerator()
    {
        return OccurredEvents.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    public void Dispatch<T>(T @event) where T : IEvent
    {
        OccurredEvents.Enqueue(@event);
    }

    public void Clear()
    {
        OccurredEvents.Clear();
    }
}

The one that glues everything together

This is a example implementation useable in your application, it uses a subscriber factory underneath (Typed Factory Facility – Castle Windsor).

public class DispatchToSubscribersEventDispatcher : IEventDispatcher
{
    private readonly ISubscriberFactory _subscriberFactory;

    public DispatchToSubscribersEventDispatcher(ISubscriberFactory subscriberFactory)
    {
        _subscriberFactory = subscriberFactory;
    }

    public void Dispatch<T>(T @event) where T : IEvent
    {
        ISubscribe<T>[] subscribers = _subscriberFactory.GetSubscribers<T>();

        try
        {
            foreach (var subscriber in subscribers)
                subscriber.On(@event);
        }
        finally
        {
            foreach (var handler in subscribers)
                _subscriberFactory.Release(handler);
        }
    }
}
Registration details for Windsor and application start code
public class EventingInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(Component.For<ISubscriberFactory>()
                                    .AsFactory());

        container.Register(Component.For<IEventDispatcher>()
                                    .ImplementedBy<DispatchToSubscribersEventDispatcher>());
    }
}

And for instance in your Global.asax after you setup your container:

var container = new WindsorContainer();
container.AddFacility(new EventingFacility());
DomainEvents.Dispatcher = container.Resolve<IEventDispatcher>();

Reference links

As usual the code and supplementary unit tests, are available on Github.

I command you

Standard

Setup

Today we are going to talk about CQS (Command Query Separation). In this blog post i will focus on the command part. Commands are simple objects that instruct our application to do something. I will show you the most simple implementation possible, combined with the power of Castle Windsor, which will act as our command handler registry. Let’s show the basic duo, namely our command and it’s respective handler.

 public interface ICommand
 {
 }

 public interface ICommandHandler<T> where T : ICommand
 {
    void Handle(T command);
 }

The ‘ICommand’ interface acts as a marker interface to mark all of our commands in our code base. Let’s take the example model from my previous blog post as a starting point for our first command:

public class MoveCustomerCommand : ICommand
{
  public int CustomerId { get; set; }
  public string Street { get; set; }
  public string StreetNumber { get; set; }
  public string PostalCode { get; set; }
  public string City { get; set; }
  public string Country { get; set; }
}

And it’s dedicated handler:

public class MoveCustomerCommandHandler : ICommandHandler<MoveCustomerCommand>
{
    private readonly ICustomerRepository _customerRepository;
    private readonly IUnitOfWork _unitOfWork;

    public MoveCustomerCommandHandler(ICustomerRepository customerRepository
                                      , IUnitOfWork unitOfWork)
    {
        _customerRepository = customerRepository;
        _unitOfWork = unitOfWork;
    }

    public void Handle(MoveCustomerCommand command)
    {
        Customer existingCustomer = _customerRepository.GetById(customer.Id);
        if (existingCustomer == null) 
           throw new InvalidOperationException("Customer does not exist");

        var newAddress = new Address(customer.Street
                                     , customer.StreetNumber
                                     , customer.PostalCode
                                     , customer.City
                                     , customer.Country);

        existingCustomer.Move(newAddress);

        _unitOfWork.SaveChanges();
    }
}

Infrastructure

Bus

The Bus acts as the primal communication point in our application, it’s responsibility is too send command’s, directly we add a single command send and a multiple command send, so we can use this later as a facade for our unitofwork/transaction setup (The more reactions i get to this post, the more i will invest in diving into the nitty bitty details ;))

public interface IBus
{
    void Send(ICommand command);
    void Send(ICommand[] commands);
}

Dispatcher

The dispatcher’s primary role is execute the handler of the command given. Later we could use this to do for instance validation on our commands.

public interface ICommandDispatcher
{
    void Dispatch<T>(T command) where T : ICommand;
}

Show me the code

A possible bus implementation, that will invoke the dispatcher’s generic dispatch method:

public class DispatchingCommandBus : IBus
{
    private readonly ICommandDispatcher _dispatcher;

    public DispatchingCommandBus(ICommandDispatcher dispatcher)
    {
        _dispatcher = dispatcher;
    }

    public virtual void Send(ICommand command)
    {
        if (command == null) return;

        MethodInfo method = typeof (ICommandDispatcher).GetMethod("Dispatch");
        MethodInfo generic = method.MakeGenericMethod(command.GetType());
        generic.Invoke(_dispatcher, new object[] {command});
    }

    public void Send(ICommand[] commands)
    {
        if (commands == null) return;

        foreach (ICommand command in commands) Send(command);
    }
}

And an example implementation of our dispatcher, which will use a commandhandler factory to get the respective handler:

public class DirectExecutingCommandDispatcher : ICommandDispatcher
{
    private readonly ICommandHandlerFactory _factory;

    public DirectExecutingCommandDispatcher(ICommandHandlerFactory factory)
    {
        _factory = factory;
    }

    public void Dispatch<T>(T command) where T : ICommand
    {
        ICommandHandler<T> handler = _factory.CreateHandler<T>();

        try
        {
            handler.Handle(command);
        }
        finally
        {
            _factory.Release(handler);
        }
    }
}

The ‘ICommandHandlerFactory’ is fully implemented by Castle Windsor’s TypedFactory facility, and if you are wondering why the release code, please read my post about understanding memory leaks with Castle Windsor.

The commanding facility

All necessary registration’s nicely molded into a custom facility :

using System.Linq;
using Castle.Core.Configuration;
using Castle.Facilities.TypedFactory;
using Castle.MicroKernel;
using Castle.MicroKernel.Facilities;
using Castle.MicroKernel.Registration;

namespace Sapphire.Commands
{
    public class CommandingFacility : IFacility
    {
        public void Init(IKernel kernel, IConfiguration facilityConfig)
        {
            AssertFacility<TypedFactoryFacility>(kernel);

            kernel.Register(Component.For<ICommandHandlerFactory>().AsFactory());

            kernel.Register(Component.For<ICommandDispatcher>()
                                     .ImplementedBy<DirectExecutingCommandDispatcher>()
                                     .LifestyleTransient());

            kernel.Register(Component.For<IBus>()
                                     .ImplementedBy<DispatchingCommandBus>()
                                     .LifestyleTransient());
        }

        public void Terminate()
        {
        }

        private void AssertFacility<T>(IKernel kernel)
        {
            if (kernel.GetFacilities().Any(f => f is T)) return;
            throw new FacilityException(string.Format("CommandingFacility is dependent on {0}", typeof (T).Name));
        }
    }
}

Wrapup

So to use this code, just register all of your commandhandlers, best with a lifestyle of transient, and add TypedFactoryFacility and CommandFacility into the mix, and start commanding away ;)

var container = new WindsorContainer();
container.AddFacility<TypedFactoryFacility>();
container.AddFacility<CommandingFacility>();

//Register all your command handlers
...

The code, and the supplementary unit tests, are available on Github.

Currying your monolithic code with basic DDD principles

Standard

Even the most monolithic code base could benefit by introducing some of the most basic principles of Domain Driven Design.  The following blog post is a reproduction of a real life code base, in a simplified form, but not far from reality.

The breakdown

public void Update(CustomerDto customer)
{
    Customer existingCustomer = _customerRepository.GetById(customer.Id);
    if (existingCustomer == null)
        throw new InvalidOperationException("Customer does not exist");

    // Check to see if we have changes
    bool hasChanges = !existingCustomer.Street.Equals(customer.Street)
                      || !existingCustomer.StreetNumber.Equals(customer.StreetNumber)
                      || !existingCustomer.City.Equals(customer.City)
                      || !existingCustomer.PostalCode.Equals(customer.PostalCode)
                      || !existingCustomer.Country.Equals(customer.Country);

    // Update object
    existingCustomer.Street = customer.Street;
    existingCustomer.StreetNumber = customer.StreetNumber;
    existingCustomer.PostalCode = customer.PostalCode;
    existingCustomer.City = customer.City;
    existingCustomer.Country = customer.Country;

    // If we have address changes update invoicing service
    if (hasChanges)
    {
        _invoicingService.Execute(new UpdateAddress
            {
                Id = customer.Id,
                Street = customer.Street,
                Number = customer.StreetNumber,
                Postal = customer.PostalCode,
                City = customer.City,
                Country = customer.Country
            });
    }

    _unitOfWork.SaveChanges();
}

By seeing the above code snippet, even without knowing all the specific implementations, we can clearly identify the requirements of this method:

  1. Map all necessary values from the data-transfer object to the domain
  2. When a customer’s address has been been changed we need inform the invoicing service of that change
  3. We need to persist the changes if any

Just for the sake of clarity i will include the initial anemic domain model

public class Customer
{
    public int Id { get; set; }
    public string Street { get; set; }
    public string StreetNumber { get; set; }
    public string PostalCode { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
}

The ‘Address’ value object

By introducing a DDD value object for all the address related properties we could simplify all the necessary change tracking in this code, i will include the Address code snippet just for clarity but i let my Resharper generate all equality members.

public class Address
{
    public Address(string street, string streetNumber, string postalCode, string city, string country)
    {
        Street = street;
        StreetNumber = streetNumber;
        PostalCode = postalCode;
        City = city;
        Country = country;
    }

    public string Street { get; private set; }
    public string StreetNumber { get; private set; }
    public string PostalCode { get; private set; }
    public string City { get; private set; }
    public string Country { get; private set; }

    protected bool Equals(Address other)
    {
        return string.Equals(Street, other.Street) && string.Equals(StreetNumber, other.StreetNumber) &&
               string.Equals(PostalCode, other.PostalCode) && string.Equals(City, other.City) &&
               string.Equals(Country, other.Country);
    }

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (obj.GetType() != typeof (Address)) return false;
        return Equals((Address) obj);
    }

    public override int GetHashCode()
    {
        unchecked
        {
            int hashCode = (Street != null ? Street.GetHashCode() : 0);
            hashCode = (hashCode*397) ^ (StreetNumber != null ? StreetNumber.GetHashCode() : 0);
            hashCode = (hashCode*397) ^ (PostalCode != null ? PostalCode.GetHashCode() : 0);
            hashCode = (hashCode*397) ^ (City != null ? City.GetHashCode() : 0);
            hashCode = (hashCode*397) ^ (Country != null ? Country.GetHashCode() : 0);
            return hashCode;
        }
    }

    public static bool operator ==(Address left, Address right)
    {
        return Equals(left, right);
    }

    public static bool operator !=(Address left, Address right)
    {
        return !Equals(left, right);
    }
}

This is how our Customer domain object could look like at this moment:

public class Customer
{
    public int Id { get; set; }
    public Address Address { get; set; }
}

By doing this we can refactor our main monolithic block to this:

public void Update(CustomerDto customer)
{
    Customer existingCustomer = _customerRepository.GetById(customer.Id);
    if (existingCustomer == null) throw new InvalidOperationException("Customer does not exist");

    // Check to see if we have changes
    var newAddress = new Address(customer.Street
                    , customer.StreetNumber
                    , customer.PostalCode
                    , customer.City
                    , customer.Country);

    bool hasChanges = existingCustomer.Address != newAddress;

    // Update object
    existingCustomer.Address = newAddress;

    // If we have address changes update invoicing service
    if (hasChanges)
    {
        _invoicingService.Execute(new UpdateAddress
            {
                Id = customer.Id,
                Street = customer.Street,
                Number = customer.StreetNumber,
                Postal = customer.PostalCode,
                City = customer.City,
                Country = customer.Country
            });
    }

    _unitOfWork.SaveChanges();
}

Introduce a domain event and put the logic where it belongs

For more details i encourage you to read Udi Dahan’s post on it.

The ‘CustomerMoved’ domain event:

This event indicates that a customer has moved

public class CustomerMoved : IDomainEvent
{
    public int Id { get; set; }
    public Address Address { get; set; }
}

It’s handler

Which has only the responsability to let the invoicing system know when a customer has moved.

public class UpdateInvoicingAddressHandler : IDomainEventHandler<CustomerMoved>
{
    private readonly InvoicingService _invoicingService;

    public UpdateInvoicingAddressHandler(InvoicingService invoicingService)
    {
        _invoicingService = invoicingService;
    }

    public void On(CustomerMoved @event)
    {
        _invoicingService.Execute(new UpdateAddress
                {
                    Id = @event.Id,
                    Street = @event.Address.Street,
                    Number = @event.Address.StreetNumber,
                    Postal = @event.Address.PostalCode,
                    City = @event.Address.City,
                    Country = @event.Address.Country
                });
    }
}

Remove setters

Let’s create a move method that does all necessary mechanics and remove the address property setter

public class Customer
{
    public int Id { get; set; }
    public Address Address { get; private set; }

    public void Move(Address newAddress)
    {
        if (Address == newAddress) return;

        Address = newAddress;

        DomainEvents.Raise(new CustomerMoved {Id = Id, Address = newAddress});
    }
}

The result, which is no longer monolithic

public void Update(CustomerDto customer)
{
    Customer existingCustomer = _customerRepository.GetById(customer.Id);
    if (existingCustomer == null) throw new InvalidOperationException("Customer does not exist");

    var newAddress = new Address(customer.Street, customer.StreetNumber, customer.PostalCode, customer.City,
                                 customer.Country);

    existingCustomer.Move(newAddress);

    _unitOfWork.SaveChanges();
}

I hope that i convinced or can inspire some of you, we could and should all benefit from the principles applied in DDD.

XP Teams: Tips and pitfalls

Standard

There is an ‘I’ in Silence

If all team members seem very occupied and don’t say a word except maybe on your daily standup meetings, then you probably don’t have a team at all. Teams that are not communicating could be developing next to each other. All those different parts of software need to form a hole, also known as your product. Good teams need to communicate whenever the need arises, form code-pairs naturally and should be having fun while working.

Domain is king

In absence of a domain expert, tackle every new story in pair. The domain of the application is the most important and the most unambiguous part of the application. Invest some time in it !

  • Use a whiteboard (or tool) to draw the basic layout of the domain needed to create.
  • Focus on naming and aggregate separation.
  • Instead of talking about properties (especially the naked primitive ones) focus on methods, associations and value objects.

Important: Domain models contain business logic and not only properties (Anemic Domain Model), no point in trying to avoid that, your domain model is specific to the project it was created for.

Stop the future developing train

Except maybe fortune tellers, no one is able to predict the future. But as it comes to developers, it seems that most of them think they are talented fortune tellers. While developing a user story, they create pieces of code they think are reusable, micro frameworks, but in reality are rarely reused. Every time you as developer start thinking: Hey I should refactor and try to make it reusable, stop it right there, wait until the need arises. (YAGNI)

The misconception of DRY

“Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.”

The DRY principle is so much abused in software development. It is abused to mold two pieces of non-related code into one, just to reuse code. Copying code once does not form a problem, because you cannot predict if two objects just seem to behave similar or have truly shared behavior. Copying the same piece, a third time should ring an alarm bell.

The chase of code coverage

Every unit test should exist to prove a functional requirement, not just to cover a piece of code perfectly. Non meaningful tests are a drag and can complicate future refactoring’s more than having only 65% of your code covered. (http://adiws.blogspot.it/2012/04/code-coverage-considered-harmful.html)

A way to avoid this is to write your tests first (TDD), but please stop finding excuses to not write tests !

Every rectangle is a square

When working in an object-oriented language, always be careful with inheritance. Use it wisely and scarce. Favor composition over inheritance. For me personally inheriting from another object means that the subtype is the base type. Never use inheritance just because objects share the same properties, it’s all about behavior not about data.

A clear example: Even though an eagle and an ostrich are both birds, only 1 of them can fly.

The hidden perfectionist

When working together on a project, there will exist different opinions on how “quality” code should look like. Sometimes there may be a need to have code reviews. The entire idea behind code reviews is that both the reviewer as the author can learn something new. If you act as the reviewer always work in pair with the author of the code. Never, and I mean never refactor the code without communication. Remember the intention is to discuss about the code not to play a game of ping-pong. Being right or wrong is just a matter of who is the beholder.