Posts in English

TDD story, part 2

After setting the environment and rethinking the workflow, it is time for some real work. So I started coding. I didn’t have to wait much for the first true effects.

I, as an architect, I decided to create process-based model. Then, as a coder, I begin coding some validation logic as an activity in the process. The activity takes a message as an input and returns true in it can be processed, false otherwise. Simple, isn’t it?

I didn’t have to come up with an API because the architect (myself, only with a different hat) had defined it already. So I proceeded to write the specification. After some struggle I realized that it will be really hard to write one. I had a dozen of validation rules written down in the analysis document and I wanted to write a specifications for each one of these separately. I don’t want that smelly code which creates a handful of  ‘exsample’ messages, validates them and checks whether result is the same as expected. That would be integration testing, not BDD-like specification.

The problem is that when rules are represented implicitly in the validation method (possibly as private sub-methods) if you want to check a single particular rule, you have to create a test object which is ‘almost valid’ — it passes all the rules except the one being tests. It is really awkward.

So, how can I do make code testable? For example, by making validation rule explicit. The need of writing a specification made me to think about validation in terms of rules to be specified and testes, not in terms of methods on a class. I created a new interface:

public interface IValidationRule
{
   bool Check(RequestForTransfer message);
}

The validation would have only to iterate through all the defined rules and check whether all of them are passing. More important, for each individual rule a specification can be written which directly implements the statements from the analysis document.

How would this end if I weren’t doing TDD? Almost certainly I would end up with validation logic encoded with one monolithic class, violating the Single Responsibility Principle. If I would have luck, individual rules would be implemented initially by different methods. But because this is not, by no means, a crisp design I would expect it to rot over time and validation logic rules to become be jumbled.

VN:F [1.8.7_1070]
Rating: 5.0/5 (1 vote cast)

TDD story, part 1

Recently I was assigned to a new project. It seemed to be yet another simple application so, to add some spice, I decided to do it the TDD/BDD way. This is a story which documents my efforts.

Work environment

Configuration of work environment was harder then I expected. Forcing Visual Studio 2008 to work properly with two monitors was a must. I really wanted to run my tests as easily as possible and have the results displayed on side monitor immediately. Instead of working IDE, I ended up with Visual Studio crashing and restarting itself whenever I tried to run the code. Finally I figured out which window caused the problem. It seems that if you use multiple monitors, you can’t use Test View. At least closing it helped in my case.

The good thing is I finally, because of lack of Test View window, learnt some keyboard shortcuts concerning running automatic tests. From the other hand I would have to do it anyway, if I wanted to run the tests after every change in code. Now, I am starting to make Ctrl+R,A a habit, just like Ctrl+S: write some code, save it and run all the tests.

You are not allowed to write any code before writing a failing test

This statement is very well known and accepted but is, in fact, completely misleading. I am sure that those of you who do TDD on a daily basis understand it correctly. But someone, like me, who wants to start his test driven journey, thinks reads it like this:

  1. Start writing a test.
  2. Accept the fact that R# makes all your code test red and you lost your Intellisense.
  3. Use R# to create missing classes and methods. Make methods throw NotImplementedException.
  4. Run the test. Wow! It fails! I finally can write some code! Hurray!

Which, of course, is completely wrong. Thanks to Derick Bailey and his great TDD blog post series I woke up very quickly. Instead of the workflow above, I started to practice something like this:

  1. Experiment with the API of a new piece of code (this step is actually a little bit controversial, but I don’t care)
  2. When satisfied, write it down with empty method bodies or returning default hard-coded values
  3. Write a specification of behavior for that API. Start with one statement.
  4. Run the specification. It fails because the assertion expected a correct value but default or hard-coded one was provided.

Start with something simple

I really really love the idea of Behavior Driven Development — specify instead of test. But I don’t want to start my TDD/BDD journey by installing the latest and coolest unit testing frameworks. I don’t want to teach my colleagues how to use it and I don’t want to scare them with these sophisticated tools. I want them to grasp the principles of TDD/BDD, not learn how to use infrastructure.

So I stick with plain MSTest. Yes, you can do BDD and write specifications of behavior using MSTest. Is is somewhat awkward, however, but is definitively possible and doesn’t break any corporate rules and habits.

VN:F [1.8.7_1070]
Rating: 5.0/5 (1 vote cast)

Dependency inversion patterns and the domain model

Inversion of control is constantly a hot topic. So are domain model and domain-driven design. How about combining these into one hot post? Yeah, combining posts is easy compared to combining the patterns. I will focus on particular type of inversion of control — the dependency inversion.

The problem

You are building a system. One day you encounter a new requirement stating that customers with unpaid dues should be notified by e-mail.

As a careful designer, you had decided that your business logic will be structured according to domain model pattern. When the new requirement comes, you instantly know how to implement it — just add CheckUnpaidDues method to the Customer entity.

On the other hand, as a conscious developer, you recognize that abstract concepts should not depend upon details. Put it another way, business logic (the Customer entity) should not depend upon infrastructure (the e-mail sending library). So you decide to make use of Uncle Bob’s dependency inversion principle.

Here is the initial solution.

public interface IEmailSender
{
   void SendEmail(string address);
}

public class Customer
{
   public string Name { get; set;}
   public string EmailAddress { get; set;}
   public IEmailSender EmailSender { get; set; }

   public void CheckUnpaidDues()
   {
      //...
      HasUnpaidDues = true;
      EmailSender.SendEmail(EmailAddress);
   }
}

Dependency injection

It solution uses dependency injection pattern. Dependencies are being ‘injected’ into a domain model object using specialized framework — the Inversion of Control (IoC) container. This causes at least two problems.

First of all, injecting dependencies into domain objects is a technically challenging task. You have to deal with your object/relational mapping (O/RM) framework, plug into it’s instance creation process and make it use your container instead of simply new-ing up objects. This, however, can be accomplished with most O/RMs, given a skillful developer and reasonable amount of time.

The far worse problem is degradation of the model. Can you spot it right away? By adding an EmailSender field/property to the Customer entity we stated that e-mail sending mechanism is a part of customer model. It is ridiculous. Real world customers don’t carry SMTP servers in a backpack, so why should we model them that way? It is obvious that other, non domain-related, concepts are creeping into the model. We should do something to prevent this.

Double dispatch

The are some doubts (see comments under this Jimmy Bogard’s blog post) about concerning the name of this pattern, but that’s not the point. What does matter is the idea of passing a dependency as an argument to the method of domain object.

public class Customer
{
   public string Name { get; set;}
   public string EmailAddress { get; set;}

   public void CheckUnpaidDuesAndNotifyUsing(IEmailSender sender)
   {
      //...
      sender.SendEmail(EmailAddress);
   }
}

What we gain here by using this pattern is a clear message stating that e-mail sending mechanism is not a part of Customer’s model, but Customer-representing entity can use it in order to send notifications.

Service Locator

We can achieve a quite similar effect using service locator pattern:

public class Customer
{
   public string Name { get; set;}
   public string EmailAddress { get; set;}

   public void CheckUnpaidDues()
   {
      //...
      ServiceLocator.Current.GetInstance<IEmailSender>()
         .SendEmail(EmailAddress);
   }
}

There is a difference, however. A very big one, actually. This code hides the dependency instead of exposing it. This is what makes service locator an anti-pattern in majority of cases. As Krzysztof recently said (and I remembered)

service locator dependency is the worst of static class dependencies because it makes out class depend on possibly anything

There is, at least in case of dependency inversion, a third way (I don’t consider a service locator a solution anymore).

Domain Events

One again I will build upon great blog post series by Udi Dahan introducing a pattern called domain events. This pattern describes a solution to the problem of pushing information out of domain model without breaking it’s encapsulation. Sounds pretty useful, isn’t it? Will it enable us to send out e-mails (push data out) without introducing dependency on e-mail sender (without breaking encapsulation). Let’s try it out.
First, the pushing data out part.

public class Customer
{
   public string Name { get; set;}
   public string EmailAddress { get; set;}
   public bool HasUnpaidDues { get; set; }

   public void CheckUnpaidDues()
   {
      //...
      HasUnpaidDues = true;
      DomainEvents.Publish(new CustomerHasUnpaidDuesEvent(this));
      return true;
   }
}

This model tells us that Customer entity is able to check whether there are any unpaid dues and, if so, publish that information for others to use. What are these others? An e-mail notifier, for example.

public class SendEmailIfCustomerHasUnpaidDues : IEventHandler<CustomerHasUnpaidDuesEvent>
{
   public IEmailSender EmailSender { get; set; }
   public void Handle(CustomerHasUnpaidDuesEvent @event)
   {
      EmailSender.SendEmail(@event.Subject.EmailAddress);
   }
}

It is obvious that this solution is slightly more complicated that a double dispatch one. Apart from the additional event handler class, users must also include the domain events infrastructure (I use the one Udi published, almost unmodified). Why pay the price of additional complexity?

I think that the benefit of having really clear and focused model is worth its price. Customer model no longer cares about the notification process which is not essential to the model. It focuses on that’s important — checking whether there are any unpaid dues.

This solution has, however, a downside. It can be used only in case of one-way communication. Attempts to use the event to carry the result back to the model (I have seen some) negate the publish semantics of the operation and make the whole model unreadable.

Summary

My own rule of thumb is to use domain events wherever possible (communication is, or can be, one way) and double dispatch in all the other cases. What’s yours?

VN:F [1.8.7_1070]
Rating: 5.0/5 (3 votes cast)

DDDSample 0.7

0.7 release of DDDSample is there. Go, download it, and say if you like it. There are now really five different versions in the package:

  • Classic with synchronous communication
  • Classic with asynchronous communication via NServiceBus (these two can be switched using compilation target)
  • CQRS using two NHibernate relational sores
  • CQRS using with relational store based on LINQ 2 SQL (not available as binary installation package, only in trunk)
  • Event Sourcing with CQRS

I really would like to hear you opinions on where the project should go now? Do you think it is finished and contains all the things it should contains? What needs to be done? What should be done first?

Installation is dead-simple when using default SQLite database, so don’t be afraid. If you have any problems, feel free to contact me via e-mail or twitter.

VN:F [1.8.7_1070]
Rating: 5.0/5 (1 vote cast)

[EN] Challenge everything

[read Polish version here]

Today, I challenge my coding style. Once again I decided to use my experience to revise my way of writing code. Here’s what I made up.

Var

Some time ago, as part of my ‘readable code’ post series, I criticized the var keyword for ist uselessness. Guess what happened since then? I changed my mind! Var is not scarring me any more. I got used to it. I was convinced by the possibility of using longer, more expressive variable names without making my code lines longer (I have a limit of about 100 characters).

Regions

Nothing changed here. Maybe I don’t like them even more then few months ago. I use regions only in exceptional cases when there is no other option (of refactoring). For example, in DDDSample.NET I use regions in ValueObject classes to hide the infrastructure code like equality operators. Once this code have been written, it is so dead simple that nobody will care about it so it could be hidden in a region.

Interface implementations

I used to wrap interface implementations in regions (as does R# by default). Recently I stopped doing this. First, I really rarely write classes that implement more than one non-infrastructure interface. Second, if I do implement an interface, it is a rare case that this class has also other, non related to that interface, public methods. There is no reason to distinguish the interface-implementing methods from all the others.

There is yet another argument against wrapping interface implementations in regions. Doing so makes it impossible to correctly lay out methods. Why?

Public methods, private methods

Unce Bob, in his excellent Clean Code convinced me that methods should be placed according to calling patterns. Caller method should be placed immediately above it’s callees. The main benefit is that one doesn’t have to scroll screen up and down to read the code. It is also a logical approach. Think about it. The relation ‘is calling’ creates far grater coupling between methods than having the same access type (private, public). Coupled methods should be placed close to each other in code, because there is big probability that readers would have to jump between them in order to understand the behaviour. Let’s look at the example. Here is how I used to write code:

public Class1()
{
   public void MethodA() {
   }
   public void MethodB() {
   }

   private void MethodA_1(){}
   private void MethodA_2(){}
   private void MethodB_1() {}
   private void MethodB_2() {}
}

And here is how I do it now:

public Class2()
{
   public void MethodA() {}
   private void MethodA_1(){}
   private void MethodA_2(){}

   public void MethodB() {}
   private void MethodB_1() {}
   private void MethodB_2() {}
}

You can see that while old style enables wrapping interfaces in region, the new one does not. I would have to wrap the whole class which is pointless.

Fields

Reading of NServiceBus code taught me that I can break the member ordering dogma (first fields, then methods). In NSB I encountered a pattern: first methods, then constructors, then fields. I was a little sceptic at first, but as time passed I got used to it and, eventually, I adopted it. I don’t know what was Udi’s original motivation, but for me the main benefit is that I open the class in my IDE and immediately I see all that is interesting — the public API. Thanks to modern IDEs chances are that I won’t need to see the fields at all when reading class code.

Constructor

Classes I write are either full-featured ones or merely data structures without any behaviour. Instances of the latter are created using good old new() operator, so constructor signature does matter. In these cases I put the constructor close to the top of the class code, probably after fields, but before properties. These pseudo-classes have classic member order.

Full-featured classes are completely different. Their instances are usually created by DI framework, and I don’t care what it needs to do it’s job. I put the constructor near the bottom, just above fields. I don’t want to see it normally, only when I need to add yet another dependency to the class.

End result

Here’s how it looks:

public MyNewClass()
{
   public void DoSomething()
   {
      HelperMethod1();
      HelperMethod2();
   }

   private void HelperMethod1()
   {
   }

   private void HelperMethod2()
   {
   }

   public void DoSomethingElse()
   {
   }

   public void MyNewClass(SomeOtherClass dependency, YetAnotherClass anotherDependency)
   {
      _dependency = dependency;
      _anotherDependency = anotherDependency;
   }

   private readonly SomeOtherClass _dependency;
   private readonly YetAnotherClass _anotherDependency;
}

What do you think about it? If anyone liked that coding style, here you can download an XML formatting specification for your ReSharper. It implements what I’ve written about plus if you have a field called ‘_logger’ it will placed on the very bottom of you class.

VN:F [1.8.7_1070]
Rating: 5.0/5 (1 vote cast)