On Friday I attended DDD eXchange 2010, a one-day software conference here in London on Domain Driven Design. This years conference focused on two themes — architectural innovation and process — and I saw talks by Eric Evans, Udi Dahan, Greg Young, Ian Cooper and Gojko Azdic discussing their various aspects. Here are some of my highlights.

The difference between a Domain and a Domain Model

Eric Evan led the keynote focusing on definitions of many of the original terms that get mixed from the blue DDD book. In particular, he clarified the difference between the domain and the domain model:

  • Domain — the business. How people actually do things.
  • Domain Model — a useful abstraction of the business, modelled in code.

One is fixed (only the business can change it), the other is flexible. It sounds really obvious, but often the terms are used interchangibly and things get messy. Most notably:

  • DDD systems never have a domain layer — they have a domain model. Go and rename your Domain namespace to DomainModel right now.
  • Ubiquitous language is created to describe the domain model — it is not just blindly dictated from the existing domain. Mark Gibaud summarized this succinctly in a tweet:

Both of these are things I have been vocal about in the past.

The difference between a Sub-Domain and a Bounded Context

Following on from the previous point, another tricky one — a subdomain is a sub-part of the business (e.g. in a banking domain, a subdomain might be loans), where bounded contexts are more concerned with things like linguistic boundaries. They are easiest to spot when two business experts use the same words to refer to different concepts.

Likewise, a generic subdomain is not a reusable code library/service (like Google Maps) — it is an area of the business with no special differentiation. Compare this versus the core domain, where the business derives its competitive advantage through differentiating itself from the market.

CQRS

Much of the morning was spent discussing Command Query Responsibility Segregation (CQRS), Event Sourcing, persistent view models, and all that entails. If you’ve kept up with Greg and Udi’s recent talks (here and here), you didn’t miss anything.

In a paper-based system…

Greg mentioned a useful tool he sometimes uses when identifying roles and events in a business system: imagine how the business would operate if it were completely free of computers.

How did they stay afloat sixty years ago when people went home sick? Records got lost, or contained mistakes? Are there any old employees around you can talk to who still remember? The answers to these questions may provide insight into how the domain should be modelled.

This also led into an interesting discussion about how the rise of the multi-user RDBMS has led businesses to expect their software to be 100% consistent (even though their business processes never historically were, before they got computers), and how difficult it is nowdays to convince businesses to embrace scary prospects like eventually-consistency and the possibility of stale data.

Aggregates synchronize through events, not method calls

Ian Cooper mentioned this briefly in his session on implementing DDD on a large insurance company project. Basically, an aggregate must never call a method on another aggregate — doing so would violate each of their consistency boundaries. Instead, an interaction like this should be modelled as a domain event, with a separate handler coordinating its own consistency boundary (e.g. a transaction) for the second aggregate.

Final thoughts

Overall I had a fantastic time, and I highly recommend anyone to attend next year. Props to the Skills Matter staff and Eric for running such a great event!

You can check out videos of all the sessions here.

Photo credits: Skills Matter DDD eXchange 2010 Flickr set

June 15th, 2010 | 2 Comments

Lately, I’ve seen a disturbing misconception about DDD crop up a couple of times in online and offline discussions. Here it is:

Ubiquitous language is sourced exclusively from the business. The developer side has no input, and must adopt whatever vocabulary they are given.

This is only true in situations where your project team is a Conformist to some upstream model. For example, if you’re developing an XML library, it’s probably best to stick to standard terms like Element and Attribute, than start inventing your own names for things.

In all other situations, however, you have more say. For example, if you’re developing a standalone business app from scratch, and a domain expert suggests a name for something that you think doesn’t quite fit, suggest a better one. Refining the ubiquitous language into a suitable abstraction is a team effort involving both developers and domain experts, and more often than not it flows back into the business as staff start to use the system. So it had better make sense!

April 18th, 2010 | 1 Comment

In defensive programming, guard clauses are used to protect your methods from invalid parameters. In design by contract, guard clauses are known as preconditions, and in domain driven design, we use them to protect invariants — unbreakable rules that form assumptions about our model:

public class BankAccount
{
    private int balance;

    public void WithDraw(int amount)
    {
        if (amount < 0)
            throw new InvalidAmountException(
                "Amount to be withdrawn must be positive.");

        if ((balance - amount) < 0)
        {
            string message = String.Format(
                "Cannot withdraw ${0}, balance is only ${1}.",
                amount, balance);

            throw new InsufficientFundsException(message);
        }

       balance -= amount;
    }
}

Unfortunately, in examples like this, the true intention of the method – actually withdrawing money – is now lost in a forest of error-checking guard clauses and exception messages. In fact, the successful path — representing 99% of executions (when there is enough money) — only accounts for 1 line in this method. So let’s refactor:

public class BankAccount
{
    private int balance;

    public void WithDraw(int amount)
    {
        ErrorIfInvalidAmount(amount);
        ErrorIfInsufficientFunds(amount);

       balance -= amount;
    }

    ...
}

By extracting these guard clauses into separate guard methods, the intention of the method becomes much clearer, and the explicit method names give a clear indication of what is being checked inside (regardless of how those checks are implemented). And we can concentrate on the main success path again.

April 8th, 2010 | 4 Comments

Here’s a code snippet showing a little habit of mine — something I do to all my domain and application services:

public interface IPortfolioRepository : IDomainService
{
    ...
}

public interface IPortfolioAdministrationService : IApplicationService
{
    ...
}

What’s in these base interfaces? Nothing. They are just labels, used to help make make object roles explicit:

public interface IApplicationService {}
public interface IDomainService {}

Why is this a good idea?

  1. It helps makes implicit concepts — e.g. this is a domain service — explicit.
  2. It grants you freedom with your class names, without having to suffix everything with Service or Event.
  3. It lets you do cool stuff like write integration tests to check all your application services are registered correctly.

They’re not only limited to services, by the way. Use them for aggregate roots, entities, value types, and other types of objects:

public interface IPortfolio : IAggregateRoot
{
    ...
}

public interface IPortfolio : IEntity
{
    ...
}

public class Money : IValueType
{
    ...
}

public class BookAddedToPortfolio : IDomainEvent
{
    ...
}

Udi Dahan’s Making Roles Explicit is a must-see presentation on this subject, if you haven’t already seen it. In fact, this example is only a small subset of what you can do with this technique.

March 31st, 2010 | 2 Comments

If you’re a new developer, one term you’ll hear used a lot is state. I remember I struggled with the idea at first, so I thought I’d write a brief introduction to the concept of state, and how it is applied to a few design and testing principles.

What is state?

Let’s use me as an example. Here are three facts that describe my current state:

  • My name is Richard.
  • I’m 23 years old.
  • I just ate some of my flatmate’s pancakes for lunch (wohoo!).
  • I’m in a pretty good mood.

In code, you might represent this as:

public class Person
{
    public string Name;
    public int Age;
    public Activity CurrentActivity;
    public bool IsHungry;
    public MoodType Mood;
}

These fields comprise my state. Some are unlikely to change (my name, for instance) while others are much more volatile (I will be hungry again in a few hours).

So you can see state changes over time. For example, my state right now is totally different than my state after 40 hours of nonstop travel from London from New Zealand — I arrived tired, and pretty frazzled. Both these states are different again than when I’m asleep.

State can be recorded, persisted (e.g. saved to a Person table in a RDBMS) and tracked over time. Usually, though, we’re only interested in the current state.

So state is just data, right?

Well… yes and no. When persisted, state becomes data, and in an object, state represents the data portion. Remember object-oriented programming combines behaviour (methods) with data (state).

But at a higher level, state represents the overall picture of an object right now, how it will behave, and what range of actions are available. A good example of this is the State Pattern from the GoF book. In their example, a TCP network connection has different states: established, closed, or listening for an incoming connection. These states are each encapsulated into an object, assigned to a field and the TCPConnection delegates behaviour to the current state:

So you can see in examples like this, state is more than just data — it affects behaviour too.

Unit testing state vs unit testing behaviour

This is something you might hear in the context of TDD and BDD. In short, testing on state means looking at an object’s visible state after something happened, and checking that all the values are correct.

bankingService.Transfer(chequeAccount, savingsAccount, 100.0);

// State-based assertions
Assert.AreEqual(0.0, cheque.Balance);
Assert.AreEqual(100.0, savings.Balance);

In comparison, testing on behaviour means using mocks to verify the expected methods are called.

bankingService.Transfer(chequeAccount, savingsAccount, 100.0);

// Behaviour-based assertions
chequeAccount.AssertWasCalled(account => account.Withdraw(100.0));
savingsAccount.AssertWasCalled(account => account.Deposit(100.0));

Generally behaviour-based testing is preferred, because:

  1. Focusing on behavioural seams (methods on interfaces) results in looser coupling, because the internal implementation of objects should change more often than the interfaces between them.
  2. The internal state of an object is private, and you shouldn’t be looking at it anyway — the basis of the Tell Don’t Ask principle.

Stateless services

An object’s state effects its behaviour. For example, when I eat, I feel full. If I eat too much, I feel sick — I can’t continue eating over and over.

Services, on the other hand, should be stateless. Imagine a dice-based random number generator. Every dice roll is a clean start — it should not retain any memory between rolls. To simplify usage and scale better, all service calls should be like this.

Another simpler example of unwanted state is services with methods like Initialize(), Start(), Connect(), Open() etc that must be called before other methods. Users of this service need to take responsibility for calling it and thus managing the lifecycle of the service — an unreasonable burden that introduces unnecessary coupling.

Explicit state transitions

One newer technique in domain-driven design is recognizing important state transitions, and making them explicit through the use of events. A simple example of this could be when your bank account balance goes below zero, its state becomes overdrawn:

public class Account
{
    public void Withdraw(Decimal amount)
    {
        balance -= amount;
        if (balance < 0)
            DomainEvents.Raise(new AccountBecameOverdrawn(this));
    }
}

This is an important state change — part of the business’s ubiquitous language that might have further implications down the line e.g. incurring overdraft fees. Udi Dahan writes a lot on this topic — it is a big help in decoupling your domain model, and is is the basis for event-sourcing CQRS.

So hopefully that starts to gives you an idea of what state is all about — more than just data!

March 29th, 2010 | 1 Comment