Posts tagged DDD

Testing strategies for business logic

Let’s talk about testing. How do you test your business logic? I spent some time thinking about it and came up with three different strategies for three different ways of implementing business logic.

CRUD

As you can read here, I think CRUD is OK for small and simple applications. You have to, however, remember what is not supported in this architecture – collections of nested objects.In the previous post I’ve written about few reason why is that. Today I will show you another one, this time related to testing. You test a CRUD application by performing a business action given some fake repository object(s) and verifying (on this fake repository) if proper objects have been created, updated and deleted.

//Arrange
var orderRepo = new FakeOrderRepository();
var orderService = new OrderService(orderRepo);

//Act
orderService.CreateNewOrder(orderData);

//Assert
var order = orderRepo.Get(id);
Assert.IsNotNull(order);
Assert.AreEqual(10, order.Value);

That’s it, no rocket science. It would be much more difficult, however, if you allowed relations between objects. In such case you would have to verify also these relations. Moreover, mocking a repository if you support relations would be much harder. You would basically had to provide an in-memory database. If you stick to simple structures, you mock a repository using a single collection and your’re done.

The classic approach to DDD

This approach is basically a compilation of what you can find in the Blue Book and in Jimmy Nilsson’s book. It is Domain-Driven Design with objects mapped to database using an Object-Relational Mapper (remember — NHibernate). These objects have properties for getting their attributes and showing them on the UI. Of course there is no dumb setters. Last but not least, there are also value objects that are used to represent attributes with complex values.

So how do you test such architecture? You take advantage of persistence ignorance of good domain model. Prepare a domain object in state you want to test by invoking normal business methods. Once it is ready, call the method you want to test. Then verify the results by using property getters.

//Arrange
var customer = new Customer("Szymon", "Pobiega");
var product = new Product("Widgets", new Money(10, new Currency("USD")));
var order = new Order(orderId, customer);
order.AddLineItem(3, product);

//Act
order.AddLineItem(1, product);

//Assert
Assert.AreEqual(2, order.LineItems.Count())

Testing value objects is even simpler because of their immutability. All you need is to call a method on it (returning a new instance of a value object) and compare it with expected value.

//Arrange
var usd = new Currency("USD");
var total = new Money(10, usd);
var toSubtract = new Money(2, usd);

//Act
var result = total.Minus(toSubtract);

//Assert
var expected = new Money(8, usd);
Assert.AreEqual(expected, result);

The trick in testing classic DDD is to not depend on your ORM to do anything for you behind the scenes. The good example is many-to-many relation. In NHibernate, if you set value only on one end and persist the entities, both ends will be set magically when you get the object from database next time. But before that, for some time the object model will be inconsistent. Good practice for such relations is have code in domain model that explicitly sets both ends of particular relation.

Another gotcha is preparing the object state. Like I said, you do it by calling normal methods. The downside of this approach is something may go wrong in this phase of test and the tested method will be given different state than expected. My personal pragmatic approach is to do nothing until it hurts. If it starts to cause major problems you can think about adding Assert calls after the object has been prepared to verify if it really is in the expected state.

Event Sourced DDD

One of the reasons I really like Event Sourcing is it doesn’t cause any (known to me) problems when testing. If I was to name the ideal types of code for testing, the first one on the list would be functional code and event sourced entities would be right behind it.

The beauty of testing event sourced objects comes from the fact that state mutations and business logic are separated. You can mutate the state (by applying an event) without any business action. That’s how entities are hydrated from the event stream in the first place. There is also an inherent beauty in definition of such tests

//Arrange
var order = new Order();
order.Apply(new ItemAddedEvent(10, productId));
order.Apply(new ItemAddedEvent(5, productId));
order.Apply(new ItemRemovedEvent(2, productId));

//Act
order.AddItem(3, productId);

//Assert
order.UncommittedEvents.Contains(new ItemAddedEvent(3, productId));

Which translates to

Given these events had happened before, when this action is called, I expect these events to be published

Nice, isn’t it?

Summary

Of course you can’t always afford to create a fully-featured event sourced solution. For simple scenarios it’s an overkill. But that’s not an excuse for not having good tests. Every approach to structuring your business logic is testable, you only have to know what constraints you have to place on the code so that testing it is a pleasure, not a pain in the back.

VN:F [1.9.13_1145]
Rating: 5.0/5 (1 vote cast)

What is CRUD?

Quite often we see criticism of Create-Read-Update-Delete solutions. There are tons of blog posts why CRUD is inferior to Domain-Driven Design. I have probably written a few of them in my life. It seems like everybody is doing proper DDD and advocating doing it so where’s the problem? I haven’t seen so many domain driven systems in the wild. If you take a look at DDD tag on StackOverflow you’ll see that most of questions are actually concerned with CRUD, not DDD solutions. So what is this CRUD?

It is an architectural style where the centre of the solution (or the lowest layer, depending on your perspective) is a package containing structures that represent data in the real world. These structures are usually mapped one-to-one to database tables using some kind of Object-Relational Mapper (NHibernate, remember?). Upper layers contain stateless service classes that operate on these structures.

Modern CRUD architectures borrow much of the terminology from Domain-Driven Design which confuses many people. You can find entities (a fancy name for a data structure), repositories (another fancy name, this time for Data Access Object pattern), domain services (place where the logic lives in CRUD) and so on. Please bear in mind that in the rest of this post I will be using these terms in context (and meaning) of CRUD, not DDD.

So, is CRUD inferior to Domain-Driven Design, like I suggested at the beginning? Not really. It has different architectural properties. It probably doesn’t scale as well when complexity grows. CRUD earned it’s really bad opinion because it can become quite messy if you don’t understand it’s essence.

And the essence of CRUD is Create-Read-Update-Delete. Period. You can do these four and only these forur operations on any entity. As you can see, there is no support in the architecture for establishing one-to-many relations. To be precise, there is no support for entities having collections of other entities. Why? Suppose you have a Parent entity that contains a list of Child entities. If you add a new Child entity to the collection, what should happen? It could be translated as “Update the Parent, Create a Child and AddRelation between Parent and Child” but also could be translated as “AddRelation between Parent and Child”. There is no language in CRUD to define logical relations between entities (like in DDD between aggregate root, entities and value objects) that can help to deal with such ambiguities.

What you can do is stick to many-to-one side of relations if you need them. Looking from Child’s perspective, the aforementioned operation would be unambiguously translated to “Create Child” if child entity doesn’t exist yet or “Read Child, Update Child” otherwise. The reference to it’s parent is part of it’s definition so Update operation can deal with it. But what if you need to get a collection of children of some entity? You can always use repository to query the data source, right?

To sum up, if you happen to build a simple system, please don’t throw DDD at it. It would be both an overkill and a mess. Remember, CRUD can be you friend if you understand it’s rules and follow them. Don’t try to make it DDD-Lite.

VN:F [1.9.13_1145]
Rating: 4.0/5 (2 votes cast)

On the Repository pattern

The Repository pattern is one of the most popular patterns of enterprise application architecture (P of EAE, a great book by Martin Fowler). The pattern was further refined in context of Domain-Driven Design by Eric Evans. Since then wars has been waged around how to implement a Repository and when to use it. Here’s my take on this subject.

First of all, Fowler’s definition of Repository

Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects

should not be treated literally. Providing a collection-like interface for relational database can be a problem much bigger than posed by most of the ‘enterprise’ systems that are being built today here and there. I would suggest a more practical ‘working’ definition like this one

  • Provides access methods to domain objects
  • It is meant to be used by command handlers
  • Returns one object or throws exception
  • If it is designed to work with Unit of Work, has no Save method. Otherwise, it has
  • The interface is placed in same assembly as domain model classes

The first line is pretty obvious, right? The second could be more problematic. In my opinion the very reason why we create repositories (and I do believe we should do it) is the ability to write more explicit code in command handlers (or whatever approach you use in Application layer). There are, however, cases where repositories can be useful outside of command handlers. When employing the classic approach to DDD (synchronous, without CQRS, EventSourcing and other cool stuff) we often have to display a domain object on screen. In such case we can use a repository to retrieve our object. It’s not a deadly sin son, I forgive you.

Returns one object or throws exception… Why? Because we don’t invoke any action on a collection of domain objects. Ever. If you want to display a grid, please create a separate class (I would call it Finder) for this purpose. I am pretty sure you don’t want to display all the data associated with a domain object on a grid, so your finder will probably retrieve only a subset of information. If you need the data only for display purposes, it can be a little bit stale, so you can add caching. If I haven’t convince you yet, think about change management. Do you really want to change your repository (which is part of Domain Model) every time you add a column on a grid on some UI form? I bet no. So please place all the finder methods outside of the repository.

But what if you want to invoke an action (change state) on a collection of object? The answer is simple. You are probably missing a real-world domain object which corresponds to this collection and should be the sole owner of the piece of data you want to change. Find that object and model it explicitly in your solution.

Because I don’t want to start flame wars about using (or not using, or abusing) Unit of Work, I try to be as neutral as possible in this matter. If you want Unit of Work, it’s OK for me, but please be as kind to remove Save methods from repositories. And if you don’t know if you wan’t to use Unit of Work or not, think if there is a chance that one of the repositories will ever be implemented using anything else than your favourite ORM (which is of course NHibernate). If so, don’t use Unit of Work because it’s abstraction will break on this one repository and so will your whole beautiful architecture.

The last line is, again, pretty obvious. Repositories are part of the Domain Model so, despite the fact they are not going to be used by domain objects, they need to be put in the same assembly to maintain logical cohesion.

I hope you enjoyed my subjective view of Repository as a pattern in Domain-Drive Design. I can’t wait to hear your opinions.

VN:F [1.9.13_1145]
Rating: 3.8/5 (5 votes cast)

Just an idea

Traditionally web applications are built using some sort of server-side framework like Rails or ASP.NET MVC. Such a framework provide means to implement business logic in a (hopefully) testable manner. Traditionally there are two approaches to shape this logic. One is to leave it close to the UI layer, probably in the Controller part of MVC pattern. The other, advocated by most Domain-Driven Design junkies, is to move it to The Model and leave Controllers as dumb as possible. As you probably already know, I am a proponent of the latter approach. Making Controllers dumb led me to an idea: how about getting rid of the controller and the web framework they are living in and letting client-side JavaScript communicate directly with the domain? Just an idea…

Draft solution

In traditionally approaches where domain entities are moved up and down through all the layers (and almost all tiers) it would be difficult to use them also on client side. That is why we are going to use CQRS as our architectural principle. The first draft solution would look like this:

Client-side JavaScript code is reacting on user input and building commands which are asynchronously sent to the remote facade sitting on the application server. Simple, isn’t it? Is has some drawbacks though.

Problems

First is that client has no means to inspect the outcome of the commands he is sending. He has to duplicate the read model code in order to update the UI widgets. Second, the commands are immediately executed upon reception by the Remote Facade and their outcome is persisted in the Event Store. If a user clicked a wrong button, it would be difficult to undo his action.

Solution, refined

How can we solve this problems? One solution that comes to my mind is to not persist command execution outcome to the event store and read model, but create an in-memory representation of updates to the read model and sent it back to the client. There is no state change on server side. Client can submit commands as user interacts with the UI and receive back the outcome in a denormalized form which can be directly and immediately bound to the UI widgets. All the commands are recorded on client side. The following diagram depicts this process.

When user wants to accept the changes he made, all the recorded commands are send to the server for ‘persistent’ execution.

Challenges

Looks nice, isn’t it? There are some challenges though. There is a lot of JavaScript code to be written to make the client-side plumbing work. There are also some design questions that need to be answered. For example, how do we specify which changes in a read model the client is interested in? Do we send all the changes or somehow ’subscribe’ for particular views in the read model? And how do we create denormalizers so that the same code can be run against both persistent and in-memory read models? We probably need a library for abstracting the read model storage implementation from the denormalizer code. These are hard problems, but I think they are worth solving. The final outcome could be very, very nice.

And it is worth notice that this approach is not limited to the thin client (JavaScript). The same architectural principles should be valid in case of both Silverlight and WPF client.

VN:F [1.9.13_1145]
Rating: 4.0/5 (3 votes cast)

Domain Driven Design, czyli programowanie przez modelowanie

Podczas 58. spotkania Krakowskiej Grupy Developerów .NET miałem przyjemność poprowadzić prezentację pt. “Domain Driven Design, czyli programowanie przez modelowanie”. Ponieważ zakładam, że nie wszyscy jesteście z Krakowa i uczestniczyliście w spotkaniu, pozwolę sobie opisać o czym mówiłem. Prezentację możecie obejrzeć lub ściągnąć (format pptx) stąd (via SlideShare), a przykłady w kodzie stąd.

Rozwiązywanie problemów

Na początku chciałbym skontrastować “klasyczne” podejście do rozwiązywania problemów z podejściem wykorzystującym model. Można to zilustrować następująco:

Podejście klasyczne

Podejście z wykorzystaniem modelu

W wersji klasycznej programista implementuje bezpośrednio wymagania, tak jak zostały one spisane przez analityka (zwykle w formie 10/100/miliona linii “The system shall…”). Dobrze, jeśli w ten proces wpleciona jest pętla sprzężenia zwrotnego, która sprawia, że implementacja pierwszych wymagań ma wpływ na dalszy przebieg procesu analizy.

W podejściu “Domain-Driven” tak naprawdę nie istnieją role analityka i programisty. Istnieje tylko jedna rola — modelarz. Modelarz zajmuje się budową modelu rzeczywistości użytecznego w rozwiązaniu konkretnego problemu. Współpracuje on bardzo blisko z ekspertami dziedzinowymi, przetwarzając posiadaną przez nich wiedzę na spójny, niesprzeczny, a co najważniejsze, wykonywalny, model. Dopiero na bazie tego modelu tworzone jest ostateczne rozwiązanie. Możemy odnaleźć dwie pętle sprzężenia zwrotnego: pierwsza dotyczy samego modelu (im więcej modelarz stworzył, tym lepiej rozumie problem), a druga modelu w kontekście aplikacji (im więcej wiemy, co ma robić aplikacja, tym lepiej wiemy, które aspekty należy dokładniej modelować).

Cechy modelu

Skoro już wiemy, do czego przydaje się model, warto się zastanowić jakie cechy powinien posiadać dobry model. Oto moja osobista lista w kategorii “model powinien być”:

Użyteczny

Nie ma sensu budowa idealnego modelu rzeczywistości, ponieważ byłby on tak samo skomplikowany jak ta rzeczywistość. Z punktu widzenia złożoności obliczeniowej jest to niewykonalne. Znane powiedzenie mówi, że wszystkie modele są błędne, ale niektóre są użyteczne. Model, który budujemy na potrzeby naszego systemu powinien odzwierciedlać tylko ten fragment rzeczywistości, w ramach którego działa ten system i tylko pod kątem czynności bezpośrednio związanych z jego funkcjonowaniem.

Hermetyczny

Model jest kodyfikacją pewnych reguł rządzących modelowanym wycinkiem rzeczywistości. Reguły te nie powinny wyciekać z modelu, co oznacza, że jego klienci (użytkownicy) nie powinni musieć o nich wiedzieć. Przykładem może być reguła, że w modelu programu HR pracownik może mieć w danym momencie co najwyżej jednego pracodawcę. To model, a nie klient, powinien zadbać o to, aby przy zmianie pracy pracownik został odłączony od poprzedniego pracodawcy.

Podatny na modyfikacje

Jest to sprzeczne z zasadą Open-Closed Principle (open for extensions, closed for modifications), jednak w przypadku modeli sprawdza się bardzo dobrze. Aby model był nadążał za szybko zmieniającą się rzeczywistością, sam także musi się zmieniać. Nie chcemy przecież, aby skostniały model aplikacji był dla organizacji jej używającej hamulcem rozwoju, prawda?

Zrozumiały

O sukcesie modelu i całego projektu decyduje, czy wszyscy jego interesariusze rozumieją przestrzeń problemu. Model powinien stanowić podstawę porozumienia i bazę dla wszędobylskiego języka (ubiquitous language) służącego do komunikacji między wykonawcami systemu (ludźmi technicznymi), a ekspertami dziedzinowymi. W dzisiejszych czasach języki programowania takie, jak C#, są na tyle elastyczne, że pisanie kodu (modelu) tak, aby był zrozumiały dla nieprogramistów nie stanowi już większego problemu.

Wydajnie implementowalny

Mimo, iż model nie powinien być zależny od jakiejkolwiek konkretnej technologii, powinien jednak być (w jakiejś technologii) wydajnie implementowalny. Nie chcemy być zależni od NHibernate czy innego ORM-a, jednak akceptowanie faktu, że model będzie przechowywany trwale w jakiejś relacyjnej bazie danych za pośrednictwem jakiegoś ORM-a pozwala zoptymalizować wiele kwestii. Nie ma sensu udawać niezależności od wszystkich aspektów technologii.

VN:F [1.9.13_1145]
Rating: 5.0/5 (2 votes cast)