Posts in English

Fractal structures

For the last few days I was mainly pair-programming (pair-refactoring to be honest) some Silverlight UI code. I must confess I really rarely write UI code these days. Actually, I don’t remember the last time I’ve written a ASP.NET control from scratch. I did write some UI for DDDSample.Net but it was not production code after all.

MVVM

When I bumped into this Model-View-View Model (MVVM) stuff, I was a little confused. Then came the moment of enlightenment. I realized I saw all of this in totally different context – in loosely coupled system architecture. Look at this:

The blue elements on the right is MVVM stuff. It contains of three classic MVVM components and an additional one — an Event Aggregator. It is used for communication between MVVM triads. Application is organized in such a way, that multiple MVVM triads form vertical slices of functionality. These slices are loosely coupled so that they can be changed independently. Actually, when you value loose coupling much, you should avoid any code sharing between slices.

The orange elements are the building blocks of DDD-based distributed application. It receives commands via Services, then it processes them in a Domain Model which is backed by a Data Store. Finally, state changes are communicated to the outside world via a Message Bus.

How do slices communicate?

They use events and (rarely) messages. The name I chose for the diagram, the Event Aggregator, is a little bit misleading, because ViewModels should be able to both publish an event (broadcast to all interested receivers) and send direct message to a concrete receiver. The only shared thing between slices is the definition of messages (sounds like SOA, isn’t it?).

Again, how does it relate to system architecture?

I think the picture says it all. View is an analog of Service interface. View Model is an analog of Domain Model. In fact, one can say that View Model is the Domain Model in the context of user interface as it models the domain of particular UI case. The model is the place where all the information lives, a Data Store if you prefer. Finally, the Event Aggregator (with mentioned earlier unicast capabilities) is an analog of a Message Bus (such as NServiceBus).

How does it work?

Let’s look at the example. There are two slices, A and B. For the purpose of the example, let A be master view (a data grid and search) and B — a details view.

User selects the row on a grid. In response to that View A to generate a command and passes it (by means of data binding) to the View Model A. The View Model validates command, processes it (updates all required properties) and, as a result, it publishes an event “SelectionChanged”.

The Event Aggregator receives the event and searches for its subscribes. It finds View Model B so it forwards the event to it. During processing of event, View Model B requests all the data it needs from the Model B and updates its own properties using retrieved values. View B is automatically updates as it is data-bound to its View Model.

Summary

As you can see, good architected applications tend to have fractal structure. Similar forms can be discovered on various levels of detail. I value such architectures very high. The coherence makes them simple and elegant.

One more thing in case you didn’t noticed. There is a trend recently to focus architecture discussion not on what’s horizontal, but on what’s vertical. As we are (hopefully and at last) moving away from waterfallish processes, we start building applications slice by slice, not layer by layer. These slices do have to have some architecture but not as much design up front. The layers are much less important. I don’t even care if all the slices have the same layers — it can be impractical. What I want to have is the conscious process of choosing the layers of each slice so it can be implemented in the simplest possible way.

VN:F [1.8.7_1070]
Rating: 0.0/5 (0 votes cast)

Why do I find Event Sourcing interesting?

What makes Event Sourcing so interesting? I it is not the free, proven, audit trial, nor the possibility of reincarnating object in any particular state it had in the history. It is also not the great performance of add-only event store. It is testability.

Why Event Sourcing makes things testable? By splitting up logic responsible for two distinct things: calculating new state of the object and applying this state change. Normally, these two operations are mixed in one business logic method like this:

public class Customer
{
    public void PlaceOrder(Product product, int quantity)
    {
        CheckProductAvailability();
        CheckCustomerCreditLimit();
        CheckSomethingElse();
        decimal price = CalculateTotalPrice(product, quantity);
        Order o = new Order(product, quantity, price);
        _orders.Add(o);
    }
    //...
}

If you read this carefully, you will see that first 4 lines contain the business logic of state change calculation. The last 2 lines, on the other hand, contain no logic at all. Now, what’s the problem with this code’s testability?

The problem becomes visible, when I want to test how PlaceOrder behaves when adding fifth order. I have to call PlaceOrder four times to prepare state of the object. That is wrong, because my test code invokes a lot of logic during preparation phase. This means that a lot of things can go wrong and nobody likes tests which fail before the actual test code gets executed.

Let’s see if PlaceOrder can be corrected using SOLID principles. Does it have exactly one reason to change? It seems like it does. When order placement logic changes, the method changes, right? Let’s dig deeper. What about the last two lines? Do they change when the rest of method changes? Well, I don’t think so. Looks like they indeed do represent a different concern. So let’s refactor them to a separate method.

public class Customer
{
    public void PlaceOrder(Product product, int quantity)
    {
        CheckProductAvailability();
        CheckCustomerCreditLimit();
        CheckSomethingElse();
        decimal price = CalculateTotalPrice(product, quantity);
        ApplyPlaceOrder(product, quantity, price);
    }
    private void ApplyPlaceOrder(Product product, int quantity, decimal price)
    {
        Order o = new Order(product, quantity, price);
        _orders.Add(o);
    }
    //...
}

Now it looks better. At least from the have one reason to change principle. But I don’t see this improved testability at all. That is because although we split the responsibilities to separate methods, we left the methods tightly coupled to one another. Lets see what we can do about this.

public class Customer
{
    public void PlaceOrder(Product product, int quantity)
    {
        CheckProductAvailability();
        CheckCustomerCreditLimit();
        CheckSomethingElse();
        decimal price = CalculateTotalPrice(product, quantity);
        Apply(new OrderPlacedEvent(product, quantity, price));
    }
    private void OnOrderPlaced(OrderPlacedEvent @event)
    {
        Order o = new Order(@event.Product, @event.Quantity, @event.Price);
        _orders.Add(o);
    }
    //...
}

We introduced a concept of event as a way of encapsulating the state change we are about to apply. Now we can represent state changes by a series of events. The other thing we did was adding the Apply method. What is it? The Apply method is the API of Event Sourcing. It is a way of communicating hey, I, the aggregate root, want to apply the state change represented by this event! Apply invokes a method to apply state change. It can do this in a variety of ways: based on convention (like On… convention in this sample), an attribute or any other. The bottom line is, Apply applies the state change and it can be called externally, for example during tested state preparation.

[TestFixture]
public class CustomerTests
{
    [Test]
    public void When_placing_fifth_order()
    {
        Product product = new Product();
        //Arrange
        Customer c = new Customer();
        c.Apply(new OrderPlacedEvent(product, 1, 10));
        c.Apply(new OrderPlacedEvent(product, 1, 10));
        c.Apply(new OrderPlacedEvent(product, 1, 10));
        c.Apply(new OrderPlacedEvent(product, 1, 10));

        //Act
        c.PlaceOrder(product, 1);

        //Assert...
    }
}

You can see that we invoke no business logic during arrange phase. We only apply predefined, known to be right, state changes. The chance something bad will happen during this phase is minimal, as we certainly tested the OnOrderPlaced method in a different test, didn’t we?

This is what I call well tested code. PlaceOrder method is always tested in isolation, no matter if it is first or fifth order. One cannot overestimate the benefits of a testable codebase. If you happen to play (or work) with Domain-Driven Design, Event Sourcing can be beneficial for you. I see it as the missing piece of puzzle — the model is finally fully testable.

VN:F [1.8.7_1070]
Rating: 0.0/5 (0 votes cast)

DDDSample.Net news

Quite a lot have happened since last DDDSample.Net information was published here. Version 0.8 was released on April 18. This is the most recent binary release of the project. It focuses on the concept of model layers which were introduced in a separate code branch.

On April 30 another branch — AutoPersistence – was added. AutoPersistence is a concept-proof exploring the possibilities of inferring persistence mapping from the model. AP uses slightly modified version of FluentNHibernate to achieve this goal. This version is currently available only in trunk.

The most recent change is a redesign of Handling aggregate in Vanilla version of DDDSample. The new design is now more aligned with book and original Java-based project.

Stay tuned!

VN:F [1.8.7_1070]
Rating: 0.0/5 (0 votes cast)

Automatic domain model persistence – halfway through

Just a quick note. There was no new post yesterday because I was busy implementing automatic persistence for domain model concept-proof. In the previous post I was writing about private field automapping. Since then I managed to implement a bunch of other concepts, including composite elements.

My fork of FluentNHibernate (automapping-fields branch) on github was updated with the most current code version.

DDDSample.NET ‘AutoPersistence’ branch uses the modified FNH to persists its domain model and it works! Without a single mapping file!

So, if everything works fine, why ‘halfway through’? That is because the code is very, very dirty and needs much work before it can be used in production.

VN:F [1.8.7_1070]
Rating: 0.0/5 (0 votes cast)

Using FluentNHibernate to automaticaly persist your domain model

Yesterday I came across the idea of totally automating domain persistence. There are out there plenty of convention-based persistence frameworks for ActiveRecord (like the Ruby on Rails one), but there is no equivalent solution for the Domain Model (as defined by Eric Evans Blue Book).

Your first thought may be that it is because domain model mapping is complicated. In fact many folks who write about Domain Model point the complexity of mapping as a key difference between DM and AR — the latter is supposed to be limited to one-to-one table to class mapping.

I disagree. In my opinion the difference lies in set of conventions and patterns used to create AR or DM models. While AR uses classes, public properties and relations, DM has its own: entities, value objects, aggregates and so on. The complexity level is comparable when sticking to DM patterns which greatly limit the set of mapping choices. This is the path I want to go.

So, my initiative is to implement Domain Model’s conventions and patterns using FluentNHibernate. I want my persistence mapping be generated straight from domain model without any external help. I want to define my conventions which will limit the possibilities so that automatic mapping is possible. In order to do this I will have to add some metadata to the model, which itself is a nice idea because it will make my models more expressive.

Every journey starts with a first step. I started with the following requirement/story

Private (and possibly readonly) fields can be automatically mapped if there is a corresponding read-only property.

This is not supported out-of-the-box by FluentNHibernate, so I had to fork it and change it. FNH uses a set of rules to map all the features of persistent class. These rules (IAutoMapper implementations) are governed by AutoMapper class. My modification extends the property mapping rule (AutoMapProperty class) so that is uses a set of access strategies to infer the access method of particular property instead of hard-coding property access. Currently (as it is a proof-of-concept) the only supported strategies are Property (formerly built-in) and CamelCase. You can download the modified version of FNH from here (GitHub).

I will be updating a DDDSample.Net branch (I have to create a new one;-)) with results of my work. The next step would be probably relations between aggregates and within an aggregate.

VN:F [1.8.7_1070]
Rating: 0.0/5 (0 votes cast)