In this blog post, I work out some of the notes I made in Greg Young’s DDD/CQRS course in Krakow Poland.
In Domain Driven Design, there are some important things to think about. In DDD, we make a difference in the following components:
- Aggregate Roots
- Entities
- Value Objects
An Aggregate root is a set of multiple things that belong to each other. The aggregate should have a name that describes the whole.
To come to a domain driven design, you should take the following steps:
- Denormalization
- Transactions –> try to avoid
- Domain service consistency –> try to avoid
- Use soft links to learn it the right way
When applying the above, you should mention the bullets below when applying them:
- Remove the bidirectional relations
- Define your aggregates
- Make sure operations only affect one aggregate at a time
- Put methods where the state is encapsulated / where the data is changed (objects should change their own state)
- A command may only mutate state and has always a
void
return value - A Query may only expose state and can’t be a
void
return value - Avoid distributed transactions to have good scalability
Even without transactions, you can provide consistency in your systems. We can do this by merging. You can do this with the following code-snippet. For convenience, I used a really ugly GOTO
statement, you should implement a recursive method to solve this in a correct way.
public class MergingHandler<T> : Consumes<T>
{
public MergingHandler(Consumes<T> next)
{
}
public void Consume(T message)
{
try
{
BEGIN:
var commit = eventStore.GetEventsSinceVersion(message.AggregateId, message.ExpectedVersion);
next.Handle(message);
foreach(var e in commit)
{
foreach(vat attempted in UnitOfWork.Current.PeekAll())
{
if(ConflictsWith(attempted, e)) throw new RealConcurrencyException();
}
}
UnitOfWork.Current.Commit();
}
catch(ConcurrencyException e) {
goto BEGIN;
}
}
}
CodeProject
I am a .NET Software Developer at Atos International. Architecture, CQRS, DDD, C#, ASP.NET, MVC3, HTML5, Jquery, WP7, WPF, ncqrs, Node.js