Real-life DDD: organise code by responsibility layers, not repositories and services

Here is a screenshot from Visual Studio from a project for a client that I have been lead developer on for the past few months. The domain (actually a bounded context within a larger ERP system) is training for an emergency services department, where staff are required to be proficient in all sorts of skills like using rescue equipment and performing first aid.

On the left is what the domain layer looked like when we began several months ago. On the right is how it looks today:

Before: repositories, specifications, services. After: responsibility layers

What do you notice? Obviously the domain model has grown bigger and more complex over time (including another 10-20 classes that didn’t fit in my screenshot). But more importantly our grouping of objects has changed.

Responsibility layers

We originally started grouping classes into namespaces based on their object type — we had separate namespaces for repositories, specifications, factories and services.

This method made sense when we just began and our domain was very small (just a handful of core objects), but did not scale as complexity grew. For example, one important aspect of the model that arose was the separation of practicing from monitoring, i.e.:

  • scheduling training tasks, choosing which skills are to be practiced, choosing who will participate etc versus
  • determining which skills a staff member is required to maintain according to their location and position, looking back and seeing when the last time they practiced skill X, applying policies to see if it’s time to practice it again, and looking at the overall operational status of individuals, teams etc

You can see this separation reflected in the screenshot on the right.

When we first put this split in, and others like it, we preserved this grouping inside each layer — e.g. we had a Practicing.Services and Monitoring.Services namespace. This dual classification felt wrong however, and led to an annoying proliferation of namespaces that required gazillions of using statements that we had to fix every time something shifted or renamed.

After a while, we pulled objects back to half a dozen big namespaces with 10-30 classes each, supplemented by a few smaller specific domain policy and state groups. These new namespaces are beginning to show the responsibility layers of our domain, and give a much clearer picture than simply grouping all the specifications together.

ASB’s new Track My Spending feature is great!

Disclaimer: I usually only write about code, and certainly this is not a product review blog, but this is something that really made my day. And their web pages end in .aspx so technically it is .NET related.

Yesterday, I came a forum post alerting ASB customers to check out their new Track My Spending online banking feature:

ASB Track My Money expense tracking (not mine)

The reason I’m so stoked about this feature is because I’ve been looking for a way of tracking where my day-to-day money is spent for a few months now.

I was considering moving banks to somewhere that supported OFX Direct Connect (so I can download my transaction logs automatically and sort them with a tool like GNUCash or Quicken), and I even started writing the foundations of a little WPF app to do it.

Now I can see pie charts and expense breakdowns just below the rest of my internet banking. What’s more is the transaction coding process is almost exactly the same as I had envisaged for my app — categorize one transaction, and it’ll automatically tag all similar transactions with the same label.

Coding transactions

To be honest, I never would’ve expected something like this from ASB — the rest of their online banking interface is pretty clunky and looks exactly the same as it did 6-7 years since I first became a customer. So it was a nice suprise to find this little gem hidden in the junk section of the online banking menus.

I’m not sure if other banks maybe already have features like this (probably even better ones), but I was very impressed anyway. So congratulations ASB, you guys hit the nail on the head and made one very satisfied customer at least!

Visual Studio: TFS or SVN?

You may have heard of the TFS MVP fiasco being talked about over the past couple of days. Aside from demonstrating how not to disagree with comments on your blog, it raised a favourite old question for .NET developers using Visual Studio: which is better — Team Foundation Server or Subversion?

Functionally, I find both TFS and SVN pretty much the same. They aren’t really, of course, but my everyday SCM needs are pretty simple, beyond branching, merging, and tagging/labelling — so it really just comes down to which one integrates into your IDE better.

At work, we use TFS 2008 for source control. I like the IDE integration with Visual Studio (well, most of it) — it’s seamless, and I really like the pending changes window for keeping track of what I’m working on.

At home, I use VisualSVN. The IDE integration with Visual Studio is almost as good as TFS, but extends out to Windows Explorer as well, courtesy of TortoiseSVN (which it uses under the hood). TortoiseSVN also has autocompletion for files and class names in the commit dialog which makes good check-in comments really easy.

So is TFS worth the license cost over VisualSVN? Maybe, if you use the work item tracking and MS Project integration. But based on my needs, I probably wouldn’t choose it.

A programmers secret weapon: the humble to-do list

A while ago I wrote a post how to lose traction on a personal software project, based on mistakes I have made myself in the past that have slowed down or even completely stopped progress. Today I want to share a tip that has greatly improved my time management since I’ve started doing it, and helped combat many “programmer’s block” moments I am notorious for.

Coming back to work

After you take a break from a coding project for a while, getting back into the groove can be difficult. Stopping for a while can be a great way to gain perspective and maybe reevaluate your goals of what the application should and shouldn’t be, but it can also be really hard starting again where you left off.

If you know you will be leaving for a while, and want to return later, you can try leaving a test failing, or some other obvious problem that needs fixing (like a syntax error), but these only keep you going in the short term. It can be difficult choosing the next big piece of functionality to work on.

Keeping an eye on the big picture

Have you ever been in the situation where, working on an application, you surround yourself with a forest of rich infrastructure code — configuration, data access, logging, UI widgets etc — and then stop and realise that’s all your application is: an empty shell that doesn’t do anything useful yet?

Or alternatively, do you ever find yourself getting lost in detail, giving unfair attention to making one little component perfect while neglecting the other 90% needed to be up and running for the alpha release?

All those little extra “clean up” tasks you want to do

While coding I’m always spotting things I want to clean up like refactorings, missing comments, source code formatting, etc. I want to finish my current task before starting something new (and can’t until I check in my current work anyway), but I do want to do these little clean ups at some stage.

All these problems really boil down to one simple question — what should I work on next?

The programmers’ to-do list

I have found from own personal experience that sitting down to cut code without a well-thought-out plan of attack is asking for trouble. As well as the examples above, I generally skip from task to task, dabbling in things I find interesting, but not gaining much real traction towards a useful application.

Over the past few months, I have discovered that keeping a detailed to-do list is a great tool for combating these problems and staying on track. The premise is very simple: take a high-level block of work — e.g. implementing a single user story — and break it down into all the little programming steps you need to do to get there, no matter how insignificant or obvious.

Here’s a dumb example snippet of a to-do list for a web app I am working on in my spare time (the whole thing runs about four pages total). You can see the ‘high level’ tasks get vaguer towards the end, because I haven’t planned them out yet, and right at the bottom there are unimportant cleanup tasks.

The key here is to be fine-grained; you want to see all the little tasks that needs to be done, and then tick them off to see your progress. Even if they are always assumed — like validation — it’s like a calendar, only useful if you know all your appointments are in there. And it doesn’t really matter where your high-level tasks start, as long as together they add up to a program that will be useful to a user.

Defer little tasks

If you think of an easy little ‘clean up’ task you’d like to do, don’t do it now — just write it down instead. Why? Because:

  • If you do it now, it could sidetrack you from your current focus
  • It might be a low priority and a poor use of your time right now
  • Instead of doing it now, it could be an easy way to get back into the groove later

For example, if you’ve got half an hour free before going somewhere, and want to spend it on your application, you don’t want to be starting fresh on some giant new piece of work. Why not spend the minutes crossing off one or two of those little clean-up tasks you’ve been meaning to do?

Planning sessions

Alternatively, if you’re not in the mood to code, you could use the time as a planning sessionand try to think of the next big task you want to achieve, and all the small steps that make it up. This is just as helpful as cutting coding, and makes you think about the big picture.

To-do list software

I’m a geek, so naturally, I want some flash tool for managing my to-do list. There are a lot to-do list applications on the web like Todoist and Remember the Milk. I tried a few, but eventually just went back to a bulleted, indented Word document because I found it by far the quickest to work with.

Working too many late nights makes you socially retarded

Working too many late nights makes you socially retarded

This Monday, we released the first of several stages in a 6-month upgrade project to a big ERP system. As with any software project, it was a big rush at the end, but particularly so this time because I was lead, and we were doing a lot of architectural improvements (which I will talk about here in a series of articles over the next few weeks).

Anyway, in the race for the deadline, I worked late nights and weekends for sixteen days in a row. The stress was fine, because I was really enjoying the work, but by the end, I found I could hardly hold a conversation with someone about anything other than the project itself. It was as if all my social skills had somehow been sapped — the mind was willing, but the tongue had nothing to talk about.

I’ve never experienced such a thing before, and it was pretty strange. It’s important not to neglect your social life when you’re working overtime to finish a project. It’s very easy to start saying no to parties and spending time with your friends, believing you’re doing a good thing by having early nights and recharging your batteries. My advice to you is DON’T. You need the distraction right now more than ever.

Hungarian notation, what do I think?

Hungarian notation, what do I think?

A girl at work asked me yesterday about whether or not encoding a variable’s type into its name — aka Hungarian Notation — was a good idea (she’s a designer who secretly wants to be a developer). I thought I might have written an article here before about it, but it seems I haven’t, so here goes.

Encoding the purpose of a variable into its name is a good idea. For example:

customerFormpasswordHashfirstNamesubmitButtonbodyHtmlerrorMessagecountries (plural = a collection of some sort)

This is just common-sense good naming.

On the other hand, I think encoding the variable’s runtime type into its name is brain-damaged — it usually doesn’t help much and just decreases code clarity. For example:

strNamestrMessageiAgearrNamesdsEmployees

I don’t think prefixes like this add any real value at all, because you could probably guess what type they are from their names and context in which they appear. Therefore they are simply clutter.

If you need them, however, then that suggests to me you have either 1) poor variable names that fail to properly explain their purpose or 2) your methods are too long and need to be refactored. Either way, fudging variable names so you can remember what type they were declared as 300 lines earlier is not the right answer, and will probably make your code even less readable.

The difference between these two naming styles is officially known as apps vs systems Hungarian notation. Joel Spolsky has a good article on the difference and how one became perverted into the other.

Windows equivalents of ps and kill commands

Windows equivalents of ps and kill commands

If you’ve ever used Unix, you’ll no doubt be well-aquainted with the commands ps and kill. On Windows, the graphical Task Manager performs these roles pretty well, but if you ever find yourself needing to resort to the command line to kill a process (e.g. for some reason on the Vista machine I am writing this on Task Manager just sits in the system tray flashing instead of opening), the Windows equivalents of ps and kill are tasklist and taskkill:

tasklist /v  - equivalent to ps aux
taskkill /f /im ncover*  - equivalent to kill -9 ncover*

AutoMapper: writing a custom IValueResolver for Gravatar

Gravatar

I’m a big fan of Jimmy Bogard’s AutoMapper – a handy little tool for fluently mapping your domain model objects to presentation model objects.

This week, I added Gravatar support to a small side-project I’m working on. For those that don’t know, Gravatar is a globally recognized avatar with a URL based on the MD5 hash of your e-mail address, e.g.:

http://www.gravatar.com/avatar/3b3be63a4c2a439b013787725dfce802.jpg

Any site that knows your e-mail address can therefore generate your Gravatar URL and show your profile pic. If you’re using AutoMapper, mapping an e-mail address to a Gravatar URL is a perfect case for a custom IValueResolver, e.g.:

Mapper.CreateMap<User, UserProfile>()    .ForMember(p => p.Username, opt => opt.MapFrom(u => u.Username))    .ForMember(p => p.About, opt => opt.MapFrom(u => u.Profile.About))    .ForMember(p => p.Location, opt => opt.MapFrom(u => u.Profile.Location))    .ForMember(p => p.Url, opt => opt.MapFrom(u => u.Profile.Url))    .ForMember(p => p.DisplayImage,               opt => opt.ResolveUsing<GravatarUrlResolver>()                         .FromMember(u => u.Profile.Email));

You can download my implementation here: GravatarUrlResolver.cs and tests (of course) here: GravatarUrlResolverTests.cs

Using NUnit to check your IoC container is set up right

One small problem I encountered when getting into Dependency Injection (DI) and Inversion of Control (IoC) was that even though all my services were now beautifully SOLID and test-driven, quite often it was all wasted because I forgot to register them in my IoC container, causing massive errors that wouldn’t be detected until runtime (oops).

Luckily, it is very easy to write a test to check everything has been registered properly. All you need is a bit of reflection to find all the interfaces in an assembly, then try to resolve them all:

[Test]
public void Should_be_able_to_resolve_all_interfaces_in_domain()
{
    var domain = Assembly.GetAssembly(typeof(Book));
    var interfaces = domain.GetTypes().Where(t => t.IsInterface);
    foreach (Type @interface in interfaces)
    {
        Assert.IsNotNull(ServiceLocator.Current.GetInstance(@interface));
    }
}

We can make this even nicer with NUnit 2.5. Instead of a for loop with multiple asserts within one test case (hmm) that can only show one failure at a time (ugh), we can use NUnit parameterized tests to automagically generate a separate test case for each interface we need to resolve:

That’s heaps easier to read (otherwise Unity’s exceptions are very terse), and we can see multiple failures in one run. To make NUnit generate this without typing them all out by hand, all you need is the new ValueSource attribute, which lets you choose a method, field or property or method that returns an IEnumerable set of objects:

public IEnumerable<Type> GetDomainInterfaces()
{
    var domain = Assembly.GetAssembly(typeof(Book));
    return domain.GetTypes().Where(t => t.IsInterface);
}

[Test]
public void Should_be_able_to_resolve_domain_service(
    [ValueSource("GetDomainInterfaces")]Type @interface)
{
    Assert.IsNotNull(ServiceLocator.Current.GetInstance(@interface));
}

Note I include this with my integration tests, because it can take a few secs to run (e.g. I keep my NHibernate ISession in the container, and building the session factory takes a long time).

Fluent Builder Pattern for classes with long-ish constructors

Last week I discovered a rather wonderful construct for objects with long constructors, e.g. immutable value types:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class UserProfile
{
    public string City { getprotected set; }
    public string Country { getprotected set; }
    public Uri Url { getprotected set; }
    public string Email { getprotected set; }
    public string Tagline { getprotected set; }
    public UserProfile(string city, string country, Uri url, string email,
        string tagline)
    {
        ...
    }
}

This constructor has bad Connascence of Position (CoP); to construct a UserProfile instance, users have to know the position of each parameter. Otherwise they might mix up the city with the country for example:

1
2
3
// Spot the bug!
var profile = new UserProfile("NZ""Wellington",
    new Uri("https://richarddingwall.name"), "[email protected]"".NET guy");

This won’t be a problem with named parameters in C# 4.0, but until then, a nice alternative is a fluent builder class as described:

1
2
3
4
5
6
UserProfile profile = new UserProfileBuilder()
    .WithCity("Wellington")
    .WithCountry("NZ")
    .WithUrl(new Uri("https://richarddingwall.name"))
    .WithEmail("[email protected]")
    .WithTagline(".NET guy");

Builders are very easy to implement. Each With method records its value and returns the current builder instance. Then we provide an implicit cast operator that finally constructs a UserProfile with all the parameters in the right places.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class UserProfileBuilder
{
    internal string City { getset; }
    internal string Country { getset; }
    // ... etc
    public UserProfileBuilder WithCity(string city)
    {
        this.City = city;
        return this;
    }
    // ... etc
    public static implicit operator UserProfile(UserProfileBuilder builder)
    {
        return new UserProfile(builder.City, builder.Country, builder.Url,
            builder.Email, builder.Tagline);
    }
}

I really like this!