Home > Articles > Programming

  • Print
  • + Share This
This chapter is from the book

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

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020