Designing Value Objects with Entity Framework

As I burn my mid-night oil, trying to wrap my head around implementation strategy for Value Objects using Entity Framework, it so turns out that with Entity framework’s fluent API, it is ridiculously easy to do the same. But before we look at the implementation details of Value Objects using Entity Framework, let’s have few words about value objects.

Value Objects are small objects with no identity. Their values represent their identity. Hence, two Value Objects with equal fields are considered to be equal. Value Objects should be Immutable.

Let’s consider a Value Object called ProductPrice.

public class ProductPrice
{
  public double Amount { set; get; }
  public string Currency { set; get; }
}

Since we would like our value object to be Immutable, we will make the properties read-only and set them during the construction.

public class ProductPrice
{
  public ProductPrice(double amount, string currency)
  {
    this.Amount = amount;
    this.Currency = currency;
  }
  public double Amount { private set; get; }
  public string Currency { private set; get; }
}

As the name suggests, ProductPrice represents the price of the Product.

public class Product: IEntity
{
  public Guid Id { get; set; }
  public string Name { get; set; }
  public Price Price { get; set; }
  public Guid CategoryId { get; set; }
}

Since the product has only one price, it would make sense to have a single table for them. In order to do so, add the following in the DBContext,

public DbSet<Product> Products { get; set; }

Entity Framework will generate one table for you called Products with the following columns

  • Id
  • Name
  • CategoryId
  • Price_Amount
  • Price_Currency

With fluent configuration you can change the name of the columns, if you don’t like them. For example, I preffer ‘PriceAmount’ over ‘Price_Amount’, hence, I did the following to configuration to change the column name.

public ProductMap()
{
  Property(a => a.Price.Amount).HasColumnName("PriceAmount");
}

And in the DBContext class add the following,

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
  modelBuilder.Configurations.Add(new ProductMap());
}

And there you go. Simple, isn’t it?

Advertisements

Implementing Repository in DDD – Part 1

Implementing Repository is fairly staright forward in DDD. There are generally two styles of implementation,
1. aggregate-dedicated repository and
2. generic repository.

An aggregate-dedicated repository will have a method per command or query; while, Generic repository will have a standard interface for every Aggregate. However, in both cases, the repository is suppose to operate at the aggregate-root level. This post will demostrate implementation of an aggregate-dedicated repository,

In your domain layer,
public class Order: IAggregateRoot
{
public Order(IOrderRepository repository)
{ ..}

public void Order(PlaceOrderCommand command)
{
..
repository.Add(this);
}
public Order Get(Guid id)
{
return repository.Single(id);
}

public IList<Order> GetOrdersByCustomer(Guid customerId)
{
return repository.Where(o=>o.CustomerId = customerId);
}
}

Application Layer,

public class OrderService
{
public void PlaceOrder(PlaceOrderCommand command)
{
this.Transaction();
var Order = new Order(new OrderRepository());
Order.PlaceOrder(command);
this.CompleteTransaction();
}
}

The Application Layer uses dependency injection to inject an instance of the repository that the aggregate uses. The aggregate-root then calls the repository internally to persists the data and retrieve data.

In this style of implementation, a dedicated repository designed for each aggregate-root. This means a little more coding up-front compared to generic repositories, as there is one repository per aggregate. Writing unit-tests might be a little more difficult. But over all, the simplicity and flexibility that this implementation brings is huge and depending on your taste, choice of tech-stacks and data-access needs it might be a very good fit for you. Definitely worth a consideration.

Application Service Design with Commands

While the design-principles of Domain Driven Design do not require you to use Commands in your Application Service, there are few merits to doing the same.

Temporal Decoupling and Autonomy

Commands can lend themselves to be issued asynchronously depending upon your Service Level Agreement and hence introduce temporal decoupling in your system, if that is what you need. If you must have your command processed reliably, these commands can further lend themselves to be serialized and stored in some kind of non-volatile storage (like a message queue) until they are processed successfully. This autonomy becomes of critical importance if you are dealing with distributed systems.

Validation

Validations are those context-independent rules that do not depend on the state of the domain objects. Business rules, on the other hand, are context-dependent (not very different from Martin Fowler’s idea of Contextual Validation). They check whether or not the command execution will result is valid state transition. Carrying out some of these context-independent validation rules on the command it-self will take the load off the domain layer by pre-filtering commands which will anyways be rejected by the domain objects.

Many people like repeating these validation rules on both places. This will bring value only of you ever need to use your domain layer not in conjunction to your application layer. Is it likely to happen in your case?

Authorization

Implementing authorization on the command side of the application is essentially asking your-self whether or not the user is allowed to issue the command. Dealing with authorization on queries is a different discussion.

Auditing

You can store the commands to capture the user’s action which then can be used for auditing purposes.

Logging

You can log commands and hence the log the user action and intention. These logs can make root-cause analysis of production issues very easy because you now have the end-to-end data to replicate the issue in your development environment.

Re-play and Undo

Commands lend themselves to be stored which can be used to redo or undo a user action if the use-case requires you to do so.

In a nutshell, commands are programmatic representation of user’s actions and intentions. Thinking of these commands as the building blocks of the application layer can open up a floodgate of interesting possibilities in your DDD architecture and bring a lot of power and flexibility to your design.

Reference

http://www.udidahan.com/2009/12/09/clarified-cqrs/

http://codebetter.com/iancooper/2011/04/27/why-use-the-command-processor-pattern-in-the-service-layer/

 

Command Query Separation

Have a look at your current application for a moment and try to split it into two parts – the ‘read-only’ side and the write side. Please notice that I have mentioned the word ‘read-only’ side. As the name suggests, the read-only side is the side of the application that is responsible for reading data from the database and displaying it on the UI. No where during the request is it supposed to save any change back to the database. Displaying data in pagable, sortable grid falls under the ‘read-only’ side of the application. Reports would fall under ‘read-only’ side. These are the requests that do not make any change to the database. In other words, it do not change the state of system

Where-as, the other side of the application i.e the write-side of the application would persist changes made by the users into the database.

Let’s say that you were to architect the read-only and the write sides of the application separately, as though they were two different systems, what would some of the design goals that you would come up with? Try to do this exercise with your current application and put down few design goals in the order of their priorities for each side.

As far as I am concerned, eighty percent of my users are going to use twenty percent of my application. Moreover, this twenty percent of the application consists primarily of the read-only side of the application. Hence, for me, some of the high priority design goals for the read-only side of my applications would be

1. Performance
2. Scalability

By no means am I attempting to suggest that the write-side of the application is any less important. In my case, it is actually the foundation for the read-side and hence is critically important for the success of the system. But, it has different design priorities. Since, it mostly deals with complex business rules and ensures non-corruption of data, some of the design goals that would top the list would be as follows,

1. Data Integrity
2. Maintainability
2. Extendibility
3. Flexibility

Clearly, the architectural needs of the read-only and write sides of my application are different in nature. Is it the same for you also? If it is, then the question we should be asking ourselves is that does it justify applying or rather imposing same architectural patterns to both sides of application just for the sake of symmetry?

Rich object graphs are ideal for write-side of the application. They result in high degree maintainable code. But they start to play nasty in situations where complex joins are needed and high performance is a priority, something that the read-only side of application needs a lot. And really! These old fashioned stored procedures and inline queries works like charm in these kind of situation. But the problem with Stored Procedures and inline query approach is that they do not provide the same kind of maintainability and data integrity that rich object graphs do. Hence, separating out the read-only and the write sides of the application and applying different architectural patterns to both can very well be the answer.

Bertrand Meyer in his book “Object Oriented Software Construction” separates an object’s methods into two categories:

Queries: Return a result and do not change the observable state of the system (are free of side effects). In other words, the read-only methods.

Commands: Change the state of a system but do not return a value. The write methods.

Meyer calls this principle the Command Query Separation. This principle, applied at architectural level leads to a clear segregation of the commands (write operations) and the queries (read-only operation) and lends itself to the flexibility of applying different architectural patterns to the very different design needs of the Command and Query sides of the application.