ReHow to create fully encapsulated Domain Models

time to read 4 min | 788 words

A while ago Udi talked about How to create fully encapsulated Domain Models. He gave a great example, but more importantly, he gave some general rules of the thumb about how to create such a system.

Those rules are, if I understand them correctly:

  • Every message should resolve to a single method call on a domain object. The message handler is responsible for setting up the environment to call this method (getting the parameters, mostly).
  • The domain model should not throw exceptions. This is mostly because attempting to handle exceptions often lead to handling too much or too little. It is easier to define all the domain operations as throwing no exceptions, in which case all exceptions are infrastructure exceptions (or bugs).
  • Communication to the outside world is done using events. To decouple the domain from the service layer.

Things that I am not sure about:

  • What are the roles of services using this model. As a simple example, when new user is created, we should send a welcome email. This involves technical services (IEmailSender, ITemplateEngine, etc) and probably a domain service as well (INotifications.SendWelcome) I am not sure where those fit in.
  • Rules - Same thing. How do I handle things like executing a set of rules in a business action?

Anyway, I thought that it would be interesting to see how I would approach Udi's sample using my own style. What I ended up with is this:

public class AddGameToCartMessageHandler : BaseMessageHandler<AddGameToCartMessage>
{
    IRepository<TradeInCart> tradesRepository;
    IRepository<Game> gamesRepository;

    public AddGameToCartMessageHandler(
        IRepository<TradeInCart> tradesRepository,
        IRepository<Game> gamesRepository)
    {
        this.tradesRepository = tradesRepository;
        this.gamesRepository = gamesRepository;
    }

    [Transaction]
    public override void Handle(AddGameToCartMessage m)
    {
        Future<TradeInCart> cart = tradesRepository.GetFuture<TradeInCart>(m.CartId); 
        Future<TradeInCart> g = gamesRepository.GetFuture<Game>(m.GameId);

        SetupErrorHandling();

        cart.Value.Add(g.Value);
    }

    private void SetupErrorHandling()
    {
        Domain.FailureEvents.GameReportedLost = delegate
        {
             Bus.Return((int) ErrorCodes.GameReportedLost);
        };     
        Domain.FailureEvents.CartIsFull = delegate
        {
            Bus.Return((int) ErrorCodes.CartIsFull);
        };

        Domain.FailureEvents.MaxNumberOfSameGamePerCartReached = delegate
        {
            Bus.Return((int) ErrorCodes.MaxNumberOfSameGamePerCartReached);
        };
    }
}

It doesn't look that different, but let us look at the details, shall we?

  • We don't deal with the session. That is duplicate code that can get quite annoying.
  • Transactions are implicit. This saves the whole (who forgot to call tx.Commit() ) again.
  • The use of futures to get both cart and game at the cost of a single call to the DB.
  • Moved error handling to a separate method.
  • We do not use events, this saves us the trouble of having to unregister them (or manage them using weak references)
  • What we can't see is that an attempt from the domain model to call a delegate that wasn't registered would raise an error. I don't believe in ignoring errors.

I am not sure what to do about the transaction when we run into a domain error. Should we assume that the domain is smart enough to revert state changes? I am pretty sure that this is not something that we would like to assume. But, does it make sense to rollback the transaction?  An attempt to add a game that was report lost should probably trigger some alert somewhere, we don't want to roll that back, obviously.

Thoughts?

More posts in "Re" series:

  1. (19 Jun 2024) Building a Database Engine in C# & .NET
  2. (05 Mar 2024) Technology & Friends - Oren Eini on the Corax Search Engine
  3. (15 Jan 2024) S06E09 - From Code Generation to Revolutionary RavenDB
  4. (02 Jan 2024) .NET Rocks Data Sharding with Oren Eini
  5. (01 Jan 2024) .NET Core podcast on RavenDB, performance and .NET
  6. (28 Aug 2023) RavenDB and High Performance with Oren Eini
  7. (17 Feb 2023) RavenDB Usage Patterns
  8. (12 Dec 2022) Software architecture with Oren Eini
  9. (17 Nov 2022) RavenDB in a Distributed Cloud Environment
  10. (25 Jul 2022) Build your own database at Cloud Lunch & Learn
  11. (15 Jul 2022) Non relational data modeling & Database engine internals
  12. (11 Apr 2022) Clean Architecture with RavenDB
  13. (14 Mar 2022) Database Security in a Hostile World
  14. (02 Mar 2022) RavenDB–a really boring database