Archive for the ‘Domain-Driven Design’ Category

Mixing async and sync in distributed systems

One of the more difficult transitions when moving from a synchronous UI to an inherently async/CQRS-based UI is the burden of figuring out what to do with all these synchronous operations. Especially when dealing with existing systems, users that expect … Continue reading 

Persisting enumeration classes with NHibernate

As part of my “Crafting Wicked Domain Models” talk, I walk through the concept of enumeration classes, yanked from Java and on Jon Skeet’s list of biggest C# mistakes (or missing features). In my talk, I leave out how to … Continue reading 

When to use NHibernate

Ayende posted some guidance on when to use NHibernate: If you are using a relational database, and you are going to do writes, you want to use NHibernate. If all you are doing are reads, you don’t need NHibernate, you … Continue reading 

Event Sourcing as a strategic advantage

Very often you hear Domain-Driven Design recommended as an approach that should not be applied except in a few key strategic scenarios. The reasons for this are quite simple: DDD is expensive. Not in the time it takes to code … Continue reading 

CodeStock 2011 Wrap-up

This past weekend, I had the pleasure of attending and speaking at the CodeStock 2011 conference. I haven’t been to a whole lot of developer-run conferences besides our own local code camps, but this one absolutely blew the others away. … Continue reading 

Drawing boundaries

For the last nine months, I’ve primarily worked on an integration systems project, where my “User Interface” are things like flat files deposited on various SFTP servers, calls to web services, “RESTful” web services and so on. If there’s one … Continue reading 

Ditching domain models for reads

Last week was a tipping point for me.  We had an issue where a production service failed because NHibernate was trying to issue thousands of UPDATE calls for domain objects that we didn’t update.  It turned out that we had added a new colum…

Container-friendly domain events

A lot of times an operation on a single aggregate root needs to result in side effects that are outside the aggregate root boundary.  There are several ways to accomplish this, such as:

  • A return parameter on the method
  • A collecting parameter
  • Domain events

We’ve used the default implementation of domain events for quite a while, but with some recent applications I’ve worked on, we’ve noticed one small design issue:

    public static class DomainEvents

It’s that big ol’ “static” piece.  Domain events are then raised explicitly by calling this static method, Raise:

public static IHandlerContainer Container { get; set; }

public static void Raise<TEvent>(TEvent args) where TEvent : IDomainEvent
{
    if (Container != null)
        Container.GetAllHandlers<TEvent>()
            .Cast<IHandler<TEvent>>()
            .ForEach(x => x.Handle(args));

Where Container in this case is just a facade over an IoC container.  The silly Cast is from this being C# 3.0 code, the contravariance of C# 4.0 would fix this.  Again, another design issue here.  The reference to the container is static.  This means that more powerful container patterns such as nested containers are out of the picture.  This is too bad, because nested containers are another great tool in the toolbox that lets us delete a lot of code that sets up contexts for things.

The problem here is that I still want to raise events in a static manner from an entity.  I don’t want to have to reference some event pipeline object thingy in my domain objects, and I’m really not keen to start injecting things.  Instead, I want a true, fire-and-forget event.

Contextual containers and disposable actions

What I need to do is allow this static method to work with a contextual, scoped piece of code.  But that’s exactly what the “using” statement allows us to do – create a scoped piece of code, that executes something at the beginning (whatever creates the IDisposable) and something at the end (the Dispose method).

To help us create this scoped context to slip in our nested container, we can take advantage of Ayende’s most brilliant piece of code ever written, the DisposableAction:

public class DisposableAction : IDisposable
{
    private readonly Action _callback;

    public DisposableAction(Action callback)
    {
        _callback = callback;
    }

    public void Dispose()
    {
        _callback();
    }
}

I can then just implement a simple method on the DomainEvents class to allow me to swap out – and then restore – the container reference:

public static IDisposable CreateContext(IHandlerContainer container)
{
    var existingContainer = Container;
    Container = container;

    return new DisposableAction(() =>
    {
        Container = existingContainer;
    });
}

I keep a reference around to the previous container, then swap out the DomainEvents’ container for the one passed in.  When this CreateContext is finished, the DisposableAction restores the previous container with a handy closure.

So how do I use this in real code?  Something like:

public void Process<T>(T message) where T : IMessage
{
    using (var nestedContainer = _container.GetNestedContainer())
    using (var unitOfWork = new UnitOfWork(_sessionSource))
    using (DomainEvents.CreateContext(new HandlerContainer(nestedContainer)))

I have several scoped items I’m using to process a message (part of a batch processing program).  Each line in a file gets processed as a single message, with its own unit of work, its own container etc.  It’s now very plain to see the context I create to process the message because I just use the C# feature that creates bounded, self-cleaning contexts: the “using” statement.

This method still isn’t thread-safe, as it still has static elements.  I’ve just allowed a scoped, nested container to be used instead of a single, global static ontainer.  Some folks mentioned patterns like event aggregators, so there are likely other patterns that can help out with the static nature of this domain events pattern.  But for now, I can harness the power and simplicity of nested containers, and keep my handy domain events around as well.

Kick It on DotNetKicks.com

Injecting services into entities

One of the comments that came up from the Strengthen your Domain series was the idea of injecting services into your entities, instead of using domain services, double dispatch or domain events.  For quite a long time, this was not easily possible technically, but some of the more mature ORM frameworks now support this scenario.

It’s a question that gets routinely asked on various ORM and DDD mailing lists, “How do I inject services into my entities”?  Even if it’s now technically possible, the answer is the same now as it was before: you don’t.

It seems like this ability could solve quite a few problems, where behavior in my entities gets too large, but I don’t want to completely remove the entry points for this behavior from my entities.  This is a good goal, but injecting services into entities (or worse, having the entity service locate them) is a wolf in sheep’s clothing.

It turns out that following this path for dependencies introduces a few not-so-obvious problems in your domain model design.

Problem 1: Confusion on what the dependency is used for

One of the design smells you’ll often find early when following dependency injection practices are services that take several dependencies whose usage is highly fractured.  One method uses dependency A, B and C, while another method uses D and E.  When changing the behavior of this class, it’s difficult to understand the nature, size and side effects of the change.

With a service in an entity constructor, the confusion can increase.  Typically, entity constructors are used to provide the invariants.  A Transaction cannot be described as such unless I provide the Transaction Type (deposit/withdrawal/transfer) and the amount.  With an additional service in the constructor, it’s not immediately clear why exactly I need this extra service.  Is it for some core behavior, or just one method or property?  When I start to modify this entity through unit tests, I now have to make a decision every time I use the entity on whether or not I need to supply this extra parameter, or just leave it null.  Typically, when a service has dependencies that are used for only certain operations, I just let the test fail and through trial and error try and figure out what is needed.  Which brings us to the next problem.

Problem 2: Difficulty testing

When a constructor requires a dependency, but only uses it for a subset of the object’s operations, then the dependency only becomes partially required.  I could supply a null value or pass in just a no-op stub, but it leaves us with a rather strange design.  This object says it needs all these parameters to do its job, but it only needs some of the parameters some of the time.  This is what I run into with an entity that takes a dependency.  The behaviors on an entity can grow over time, but a constructor usually stays fairly static.  Once the invariants are determined, these aren’t likely to change much over time.

As behaviors grow, some operations may need to rely on services.  For unrelated operations on an entity, I don’t want to be effectively punished for the complexity required in a separate operation.  Forcing me to supply a constructor dependency introduces pain.

Solutions

I have found that optional dependencies seem to fit just fine with entities.  For example, if I want to integrate logging into my operations, I can fairly easily implement the Null Object pattern, and allow my entity to be used without that optional dependency.  Because that logging class might be supplied as a property, it communicates explicitly that this dependency is not required.

Otherwise, I’ll stick to the more obvious solutions of domain services, double dispatch and domain events.  Injecting services into entities just makes them harder to understand and use.

Kick It on DotNetKicks.com

Strengthening your domain: Domain Events

Previous posts in this series:

In the last post, we rounded out fully encapsulated domain models by encapsulating certain state information that requires certain restrictions in how that information can change.  In our model of customers, fees and payments, we started recording fee balance on the Fee object.  Once we did this, we started to lock down the public interface of our Fee and Payment objects, so that only operations supported and validated by our domain experts can be executed.  The side benefit of this sort of design is that our domain model now strongly reinforces the ubiquitous language.

In an anemic domain model, the ubiquitous language only reflects state information.  In our conversations with the domain experts, we are very likely to hear behavioral information as well.  We can talk about our model in a more cogent manner now that we have methods like “Customer.ChargeFee” and “Fee.RecordPayment”.  Merely having public setters for state information loses the context of why that information changed, and in what context it is valid for that information to change.

As we move towards a fully encapsulated domain model, we may start to encounter a very critical word in our conversations with the domain experts: When.  One of the features requested for our Customer object is:

We need to know if a customer has an outstanding balance on more than 3 fees. If a Customer has more than 3 fees with an outstanding balance, we flag them as AtRisk.  When a customer pays off a fee and they no longer have more than 3 fees outstanding, they are no longer at risk.

Note that final sentence and the implied interaction.  When a fee as been paid off, the customer needs to be notified that to update their AtRisk flag.  Whenever we hear the word “When”, that should be a signal to us that there is a potential event in our system.  We would like to model this event explicitly in our system and to have our model reflect this kind of relationship between Fee and Customer.  In our case, we’re going to use a design from Udi Dahan, Domain Events.

Introducing Domain Events

So what are domain events?  Domain events are similar to messaging-style eventing, with one key difference.  With true messaging and a service bus, a message is fired and handled to asynchronously.  With domain events, the response is synchronous.  Using domain events is rather straight forward.  In our system, we just need to know when a Fee has been paid off.  Luckily, our design up to this point has already captured the explicit operation in the Fee object, the RecordPayment method. In this method, we’ll raise an event if the Balance is zero:

public Payment RecordPayment(decimal paymentAmount, IBalanceCalculator balanceCalculator)
{
    var payment = new Payment(paymentAmount, this);

    _payments.Add(payment);

    Balance = balanceCalculator.Calculate(this);

    if (Balance == 0)
        DomainEvents.Raise(new FeePaidOff(this));

    return payment;
}

After the Balance has been updated, we raise a domain event using the DomainEvents static class.  The name of the event is very explicit and comes from the ubiquitous language, “FeePaidOff”.  We include the Fee that was paid off as part of the event message:

public class FeePaidOff : IDomainEvent
{
    public FeePaidOff(Fee fee)
    {
        Fee = fee;
    }

    public Fee Fee { get; private set; }
}

When it comes to testing the events, we have two kinds of tests we want to write.  First, we want to write a test that ensures that our Fee raised the correct event:

[Test]
public void Should_notify_when_the_balance_is_paid_off()
{
    Fee paidOffFee = null;

    DomainEvents.Register<FeePaidOff>(e => paidOffFee = e.Fee);

    var customer = new Customer();

    var fee = customer.ChargeFee(100m);

    fee.RecordPayment(100m, new BalanceCalculator());

    paidOffFee.ShouldEqual(fee);
}

We’re not checking the Customer “IsAtRisk” flag in this case, as we’re only testing the Fee object in isolation.  In an integration test, we’ll have our IoC container in the mix, and we’ll test the handlers as part of the complete operation.  Some might argue that the complete model now includes the container, and we want to test the complete operation, events and all in our unit test.  I can’t really argue against that, as you might define “unit” to now include the entire domain model, not just one entity.

Handling the event

To handle the event, we want to update the Customer’s AtRisk status for the Customer charged for the paid-off Fee.  Our handler then becomes:

public class FeePaidOffHandler : IHandler<FeePaidOff>
{
    private readonly ICustomerRepository _customerRepository;

    public FeePaidOffHandler(ICustomerRepository customerRepository)
    {
        _customerRepository = customerRepository;
    }

    public void Handle(FeePaidOff args)
    {
        var fee = args.Fee;

        var customer = _customerRepository.GetCustomerChargedForFee(fee);

        customer.UpdateAtRiskStatus();
    }
}

Because our handlers are pulled from the container, we can use normal dependency injection to process the event.  If we were going the transaction script route, we would likely see this updating in some sort of application service.  With our event handler, we ensure that our model stays consistent.  The UpdateAtRiskStatus on Customer now can apply our original business logic:

public bool IsAtRisk { get; private set; }

public void UpdateAtRiskStatus()
{
    var totalWithOutstandingBalance = Fees.Count(fee => fee.HasOutstandingBalance());

    IsAtRisk = totalWithOutstandingBalance > 3;
}

With our domain event in place, we can ensure that our entire domain model stays consistent with the business rules applied, even when we need to notify other aggregate roots in our system when something happens.  We’ve also locked down all the ways the risk status could change (charged a new fee), so we can keep our Customer aggregate consistent even in the face of changes in a separate aggregate (Fee).

This pattern isn’t always applicable.  If I need to do something like send an email, notify a web service or any other potentially blocking tasks, I should revert back to normal asynchronous messaging.  But for synchronous messaging across disconnected aggregates, domain events are a great way to ensure aggregate root consistency across the entire model.  The alternative would be transaction script design, where consistency is enforced not by the domain model but by some other (non-intuitive) layer.

Strengthening your domain: conclusion

Creating consistent aggregate root boundaries with a fully encapsulated domain model isn’t that hard, if you know what code smells to look for.  You can run into issues with less-mature ORMs that do not truly support a POCO domain model.  Having a fully encapsulated domain model represents the entirety of the ubiquitous language: state AND behavior.  Anemic domain models only tell half the picture in representing only the state.

Fully encapsulated domain models ensure that my domain model remains self-consistent, and that all invariants are satisfied at the completion of an operation.  Anemic domain models do not enforce consistency rules, and rely on reams of services to keep the model valid.

For many, many applications, a domain model is more trouble than it is worth, as the behavior of these services can be quite simple.  However, much of DDD is just plain good OOP, and a well-crafted domain model can be realized simply by paying attention to code smells and refactoring.

Kick It on DotNetKicks.com