Tuesday, January 20, 2015

More better code

I took a piece of code today and applied some techniques from the book "Clean Code" by Robert C. Martin. I have to say that I really like the results!

It was a test, it was only a test. I only applied some of the conventions regarding class and method style. I took some code from Microsoft's - MSDN - CQRS Journey and did a little refactoring. The result was an easy to understand class and methods with new classes that handled some of the responsibilities in a more SRP sort of way.

So the following code from here https://github.com/mspnp/cqrs-journey-code/blob/master/source/Infrastructure/Infrastructure/Messaging/Handling/EventDispatcher.cs

public void Register(IEventHandler handler)
{
var handlerType = handler.GetType();

foreach (var invocationTuple in this.BuildHandlerInvocations(handler))
{
var envelopeType = typeof(Envelope<>).MakeGenericType(invocationTuple.Item1);

List<Tuple<Type, Action<Envelope>>> invocations;
if (!this.handlersByEventType.TryGetValue(invocationTuple.Item1, out invocations))
{
invocations = new List<Tuple<Type, Action<Envelope>>>();
this.handlersByEventType[invocationTuple.Item1] = invocations;
}
invocations.Add(new Tuple<Type, Action<Envelope>>(handlerType, invocationTuple.Item2));

if (!this.dispatchersByEventType.ContainsKey(invocationTuple.Item1))
{
this.dispatchersByEventType[invocationTuple.Item1] = this.BuildDispatchInvocation(invocationTuple.Item1);
}
}
}

becomes

public void Register(IEventHandler handler)
{
foreach (var invocationDTO in this.BuildHandlerInvocations(handler))
{
this.RegisterHandlers(invocationDTO);
this.ReqisterDispatchers(invocationDTO)
}
}

which is far simpler to read and understand. I've extracted the details into Domain Specific Language represented by private methods.

This is part of the essence of writing clean code.

No comments:

Post a Comment