Home > Articles > Software Development & Management

  • Print
  • + Share This
  • 💬 Discuss

Domain Patterns

Domain Patterns have a very different focus from the Design Patterns and the Architectural Patterns. The focus is totally on how to structure the Domain Model itself, how to encapsulate the domain knowledge in the model, and how to apply the ubiquitous language and not let the infrastructure distract away from the important parts.

There is some overlap with Design Patterns, such as the Design Pattern called Strategy, [GoF Design Patterns] which is considered to be a Domain Pattern as well. The reason for the overlap is that patterns such as Strategy are very good tools for structuring the Domain Model.

As Design Patterns, they are technical and general. As Domain Patterns, they focus on the very core of the Domain Model. They are about making the Domain Model clearer, more expressive, and purposeful, as well as letting the knowledge gained of the domain be apparent in the Domain Model.

When I ended the previous section, I mentioned that the Specification pattern as a Domain Pattern is an alternative to Query Objects pattern. I think that’s a good way of explaining how I see what Domain Patterns are. Query Objects is a technical pattern where the consumer can define a query with a syntax based on objects, for finding more or less any of the objects in the Domain Model. The Specification pattern can be used for querying as well, but instead of using a generic query object and setting criteria, one by one, a specification is used as a concept that itself encapsulates domain knowledge and communicates the purpose.

For example, for finding the gold customers, you can use both query objects and specifications, but the solutions will differ. With Query Objects, you will express criteria about how you define gold customers. With a Specification, you will have a class that is perhaps called GoldCustomerSpecification. The criteria itself isn’t revealed or duplicated in that case, but encapsulated in that class with a well-describing name.

One source of Domain Patterns is [Arlow/Neustadt Archetype Patterns], but I have chosen a Domain Pattern-example from another good source, Eric Evans’ book Domain Driven Design [Evans DDD]. The chosen example pattern is called Factory.

An Example: Factory

Who said that the software industry is influenced by industrialism? It’s debatable whether it’s good, but it is influenced. We talk about engineering as a good principle for software development; we talk about architecture, product lines and so on and so forth. Here is another such influence, the Factory pattern. But first, let’s state the problem that goes with this example.

Problem

The problem this time is that the construction of an order is complex. It needs to be done in two very different flavors. The first is when a new order is created that is unknown to the database. The second is when the consumer asks for an old order to be materialized into the Domain Model from the database. In both cases, there needs to be an order instance created, but the similarity ends there as far as the construction goes.

Another part of the problem is that an order should always have a customer; otherwise, creating the order just doesn’t make sense. Yet another part of the problem is that we need to be able to create new credit orders and repeated orders.

Solution Proposal One

The simplest solution to the problem is to just use a public constructor like this:

public Order()

Then, after having called this constructor, the consumer has to set up the properties of the instance the way it should be to be inserted or by asking the database for the values.

Unfortunately, this is like opening a can of worms. For example, we might have dirty tracking on properties, and we probably don’t want the dirty tracking to signal an instance that was just reconstituted from persistence as dirty. Another problem is how to set the identification, which is probably not settable at all. Reflection can solve both problems (at least if the identifier isn’t declared as readonly), but is that something the Domain Model consumer developer should have to care about? I definitely don’t think so. There are some more esoteric solutions we could explore, but I’m sure most of you would agree that a typical and obvious solution would be to use parameterized constructors instead.

Because I have spent a lot of programming time in the past a long time ago with VB6, I haven’t been spoiled by parameterized constructors. Can you believe that—not having parameterized constructors? I’m actually having a hard time believing it myself.

Anyway, in C# and Java and so on, we do have the possibility of parameterized constructors, and that is probably the first solution to consider in dealing with the problem. So let’s use three public constructors of the Order class:

public Order(Customer customer);
public Order(Order order, 
      bool trueForCreditFalseForRepeat);
public Order(int orderId);

The first two constructors are used when creating a new instance of an Order that isn’t in the database yet. The first of them is for creating a new, ordinary Order. So far, so good, but I have delayed introducing requirements on purpose, making it possible to create Orders that start as reservations. When that requirement is added, the first constructor will have to change to be possible to use for two different purposes.

The second constructor is for creating either a credit Order or a repetition of an old Order. This is definitely less clear than I would like it to be.

The last constructor is used when fetching an old Order, but the only thing that reveals which constructor to use is the parameter. This is not clear. Another problem (especially with the third constructor) is that it’s considered bad practice to have lots of processing in the constructor. A jump to the database feels very bad.

Solution Proposal Two

According to the book Effective Java [Bloch Effective Java], the first item (best practice) out of 57 is to consider providing static Factory methods instead of constructors. It could look like this:

public static Order Create(Customer customer);
public static Order CreateReservation(Customer customer);
public static Order CreateCredit(Order orderToCredit);
public static Order CreateRepeat(Order orderToRepeat);
public static Order Get(int orderId);

A nice thing about such a Factory method is that it has a name, revealing its intention. For example, the fifth method is a lot clearer than its constructor counterpart from solution 1, constructor three, right? I actually think that’s the case for all the previous Factory methods when compared to solution 1, and now I added the requirement of reservations and repeating orders without getting into construction problems.

Bloch also discusses that static Factory methods don’t have to create a new instance each time they get involved, which might be big advantage. Another advantage, and a more typical one, is that they can return an instance of any subtype of their return type.

Are there any drawbacks? I think the main one is that I’m probably violating the SRP [Martin PPP] when I have my creational code in the class itself. Evans’ book [Evans DDD] is a good reminder of that where he uses a metaphor of a car engine. The car engine itself doesn’t know how it is created; that’s not its responsibility. Imagine how much more complex the engine would have to be if it not only had to operate but also had to create itself first. This argument is especially valid in cases where the creational code is complex.

Add to that metaphor the element that the engine could also be fetched from another location, such as from the shelf of a local or a central stock; that is, an old instance should be reconstituted by fetching it from the database and materializing it. This is totally different from creating the instance in the first place, both for a real, physical engine and for an Order instance in software.

We are close to the pattern solution now. Let’s use a solution similar to the second proposal, but factor out the creational behavior into a class of its own, forgetting about the "fetch from database" for now (which is dealt with by another Domain Pattern called Repository, which we will discuss a lot in later chapters).

Solution Proposal Three

So now we have come to using the Factory pattern as the Domain Pattern. Let’s start with a diagram, found in Figure 2-7.

Figure 2.7

Figure 2-7 An instance diagram for the Factory pattern

The code could look like this from a consumer perspective to obtain a ready-made new Order instance:

anOrder = OrderFactory.Create(aCustomer);
aReservation = OrderFactory.CreateReservation(aCustomer);


aCredit = OrderFactory.CreateCredit(anOldOrder);
aRepeat = OrderFactory.CreateRepeat(anOldOrder);

This is not much harder for the consumer than it is using an ordinary constructor. It’s a little bit more intrusive, but not much.

In order for the consumer to get to an old Order, the consumer must talk to something else (not the Factory, but a Repository). That’s clearer and expressive, but it’s another story for later on.

To avoid the instantiation of orders via the constructor from other classes in the Domain Model if the Factory code is in an external class is not possible, but you can make it a little less of a problem by making the constructor internal, and hopefully because the Factory is there, the Domain Model developers themselves understand that that’s the way of instantiating the class and not using the constructor of the target class directly.

More Comments

First of all, please note that sometimes a constructor is just what we want. For example, there might not be any interesting hierarchy, the client wants to choose the implementation, the construction is very simple, and the client will have access to all properties. It’s important to understand not to just go on and create factories to create each and every instance, but to use factories where they help you out and add clarity to and reveal the intention of the Domain Model.

What is typical of the Factory is that it sets up the instance in a valid state. One thing I have become pretty fond of doing is setting up the sub-instances with Null Objects [Woolf Null Object] if that’s appropriate. Take an Order, for example. Assume that the shipment of an Order is taken care of by a Transporter.

At first, the Order hasn’t been shipped (and in this case we have not thought much about shipment at all), so we can’t give it any Transporter object, but instead of just leaving the Transporter property as null, I set the property to the empty ("not chosen," perhaps) Transporter instead. In this way, I can always expect to find a description for the Transporter property like this:

anOrder.Transporter.Description

If Transporter had been null, I would have needed to check for that first. The Factory is a very handy solution for things like this. (You could do the same thing in the case of a constructor, but there might be many places you need to apply Null Objects, and it might not be trivial to decide on what to use for Null Objects if there are options. What I’m getting at is that the complexity of the constructor increases.)

You can, of course, have several different Factory methods and let them take many parameters so you get good control of the creation from the outside of the Factory.

Using Factories can also hide infrastructure requirements that you can’t avoid.

It’s extremely common to hear about Factories and see them used in a less semantic way, or at least differently so that all instances (new or "old") are created with Factories. In COM for example, every class has to have a class factory, as do many frameworks. Then it’s not the Domain Pattern Factory that is used: similar in name and in technique, different in intention.

Another example is that you can (indirectly) let the Factory go to the database to fetch default values. Again, it’s good practice to not have much processing in constructors, so they are not a good place to have logic like that.

Overall, I think the usage of the Factory pattern clearly demonstrated that some instantiation complexity was moved from the Order into a concept of its own. This also helped the clarity of the Domain Model to some degree. It’s a good clue that the instantiation logic is interesting and complex.

  • + Share This
  • 🔖 Save To Your Account

Discussions

comments powered by Disqus