Modeling in Code
For us, modeling is not reduced to drawing diagrams. If your ultimate goal is to develop software, then, at some point, you need to move from modeling with sticky notes and diagrams to modeling in programming languages. Doing that, you should use terms from the domain directly in your code.
This chapter is for you, if you want to do the following:
-
Implement your domain model as object-oriented code
-
Implement your domain model as functional code
-
Use DDD’s tactical design
In this chapter, we will come across some software development terms and concepts that we will explain only briefly. For more details, please see the references provided. In particular, we recommend the following prior knowledge:
-
This is the only chapter that contains source code. To make the best of it, you should be able to read code. We will show examples in Java and F# .
-
Building blocks for tactical DDD: entity , value object , etc. [ Evans 2004 ].
-
Practices and technologies from test-driven development/Behavior-Driven Development: unit test , acceptance test [ Beck 2000 ], JUnit , and Gherkin [ SmartBear 2019 ].
-
Familiarity with UML class diagram and state diagram [ Fowler 2004 ].
Henning’s Tax Accounting Story
I was working with a client that offers an off-the-shelf accounting software solution for small- and medium-sized companies in Germany. The system had been around for three decades and was based on technology in C++. When tax laws changed, the system had to be adapted. The company took this as an opportunity to redesign parts of the system using DDD. As a first step, we sketched COARSE-GRAINED domain stories on a whiteboard. From those we extracted a good context map.
One team built the bounded context dealing with the taxation aspects of sending employees abroad. Since German tax law is notoriously complex, we had to delve deep into the subject. (One literally has to deal with words like “Versendungsabwesenheitsantrag.”)
The accounting software company had in-house experts for that subject matter, because it also sends employees abroad. In a two-day workshop with these experts and the developers from the team, we modeled about five FINE-GRAINED domain stories. Each domain story described one specific case of the bounded context’s business process.
Since the technology and programming language were a given, we decided to model the domain with object-oriented means, using the DDD building blocks. For every important work object I asked the team the questions “Is this a thing or a value?” or “Does it have an identity?” to separate entities and value objects. Then I asked “Which work objects should be stored together (in the to-be-built system)?” to find the aggregate boundaries and repositories.
For example, we derived an entity Versendung (which roughly translates to “foreign work assignment”), a value object Einkommensteuer (“income tax”), a repository for the foreign assignments, and an application service StelleAntrag (“file application”). Finally, we implemented a first prototype of the domain model in C++ in a mob programming session.
In the next sprints, we iterated over and over again on domain stories, model, and implementation.
From Domain Stories to Domain Model
Collaborative modeling uncovers a lot of knowledge about a domain. To transform this knowledge into software, it must be condensed in a way that is close to software. A domain model is one such condensed form of knowledge. It contains the concepts of a domain: physical or purely conceptual things like “contract,” “risk,” or “voting result.” In Domain Storytelling, we call those work objects (see Chapter 2 , “ The Pictographic Language ”).
In addition to these structural aspects of a domain, the domain model also describes the behavior of the concepts. These are the activities such as “to sign” or “to vote” that tell us what the work objects can do, what can be done with them, and how other work objects can interact with them.
Domain Logic Patterns
Designing a fully-fledged domain model is one of several architectural styles that are used to implement the domain layer 1 of an application. These so-called domain logic patterns are listed here:
1 . Layered architecture [ Buschmann et al. 1996 ] was the state of the art when DDD was conceived, and the name domain layer dates from that time. In the meantime, the community has learned that the “above/below” distinction of the layered architecture is not sufficient to imagine what we want the architecture to be. That’s why today we tend to also use the “inside/outside” distinction. This is expressed in the more elaborate styles Hexagonal [ Cockburn 2005 ], Onion [ Palermo 2008 ], and Clean Architecture [ Martin 2018 ]. Thus, the domain “layer” (like other “layers”) we’re talking about is actually more of a domain “ring.” Since the term “layer” is still the one used throughout the industry, we will stick to it in this chapter.
-
Transaction script
-
Table module
-
Anemic domain model
-
Domain model
A certain familiarity with these patterns is not required but can help you understand the rest of this chapter. Good books on this subject are Patterns of Enterprise Application Architecture [ Fowler 2003c ] and Patterns, Principles, and Practices of Domain-Driven Design [ Millet/Tune 2015 ].
For every bounded context of a system a different style can be chosen. The style domain model is the typical choice for the core domain(s). 2
2 . A core domain is a bounded context that is essential to a company, i.e., a real business asset [ Evans 2004 ].
When you start writing code without knowing the domain properly, your domain model will most likely be anemic [ Fowler 2003a ]; it will be data-centric with operations to manipulate the data. Let’s look at an anemic example from Alphorn: a class Leasing - Contract with a method setSignatureDate ( LocalDate date ) (see Figure 12.1 ).
Figure 12.1 Don’t: Build an anemic domain model
Although this model may be adequate for a trivial bounded context, it has flaws: The signature date can at all times be set to any value. But in the “offering” bounded context, a contract can be signed only if (a) the installment has been calculated and (b) it has not already been signed. This is a business rule , also referred to as a policy .
A good domain model prevents programmers (and users) from breaking the rules of the domain.
A strong behavioral model is expressive and reflects the domain. Instead of an anemic pile of variables that change their values, a rich behavioral model ensures integrity and consistency with invariants . To achieve that, one must understand what happens in the domain—and look at the verbs . These are the right questions to ask:
-
What are the users doing to achieve their goals?
-
How do users handle the work objects?
-
In which way do they manipulate them?
-
How do users exchange information and work together?
These are also the questions that a moderator asks in a Domain Storytelling workshop.
Domain stories are a great resource for a domain model because they contain the structural and behavioral aspects of a domain. You can distill the domain model from one or several stories (typically a handful). You need the right level of detail, i.e., FINE-GRAINED domain stories at sea to fish level (see Chapter 4 , “ Scope ”) that take place within one bounded context (see Chapter 10 , “ Finding Boundaries ”). Maybe you have modeled such domain stories during a requirements workshop (see Chapter 11 , “ Working with Requirements ”) and you also have written requirements as input for the domain model.
Now that you know what to distill, the question is, how do you express the domain model? One possible answer is: directly in code! However, sometimes it makes sense to express it in an intermediate format first. Such intermediate formats can be any of the following:
-
Behavior-Driven Development (BDD) style scenarios [ North 2006 ]
-
Formal modeling languages like UML (usually class diagrams ) [ Fowler 2004 ]
-
Class, responsibilities, collaborators (CRC) cards [ Beck/Cunningham 1989 ]
-
Design-level EventStorming [ Brandolini 2021 ]
It is important to understand that the purpose of a domain model is not just to preserve domain knowledge. The purpose of domain modeling is to design software that expresses the domain. Getting a design right is an iterative, incremental process. Sometimes, the refinement requires continued coding; sometimes you have to go back to modeling with domain experts. Eric Evans describes this process as a model exploration whirlpool [ Evans 2016 ].
Back to the Leasing Example
Let’s look at the Alphorn example again. In Chapter 10 , “ Finding Boundaries ,” we have modeled the COARSE-GRAINED domain story with bounded contexts Alphorn 1a. We’re focusing on the context “offering” now (see Figure 12.2 ).
Figure 12.2 Alphorn1a: Leasing subdomains, focus on“offering”
In a follow-up workshop with developers Dave and Denise and domain expert Sandy, we modeled two FINE-GRAINED domain stories (see Chapter 11 , “ Working with Requirements ”), showing two variants of “Offering a contract” (reprinted in Figures 12.3 and 12.4 ).
Figure 12.3 Alphorn 6: Offering, happy path— FINE-GRAINED
Figure 12.4 Alphorn 7: Offering, rejection— FINE-GRAINED
We will now examine the domain model for the bounded context “offering.” The team starts with the user story “calculate monthly installment for new contract” from their product backlog (see Figure 11.8 ).
Refining Scenarios—From Domain Story to Acceptance Test
Before you start implementing the domain model, you want to make sure you understand the requirements that the software has to meet. You can start this discussion with domain stories and then continue it in the form of acceptance tests . You can use them later to check whether the software meets the requirements. It is easy to derive BDD-style acceptance tests from a FINE-GRAINED domain story. Listing 12.1 shows the first draft for the “happy path offering scenario” from Alphorn 6 (see Figure 12.3 ) written in the Gherkin format [ SmartBear 2019 ].
Listing 12.1 Acceptance Test for Alphorn 6, Sentence 2
Click here to view code image
1 Scenario: Calculation of a car leasing contract
2 Given a filled out contract
3 And the price is X
4 And the term is Y
5 And the interest is Z
6 When the contract is calculated
7 Then the installment is W EUR
To turn this scenario description into an acceptance test, we need to think about concrete values for the parameters. Domain stories are usually not modeled in this granularity. Hence, we need some additional input from our domain expert Sandy, the salesperson, to complete the scenario (see Listing 12.2 ).
Listing 12.2 Acceptance Test for Alphorn 6, Sentence 2, with Concrete Values
Click here to view code image
1 Scenario: Calculation of a contract for a midsize car
2 Given a filled out contract
3 And the price is EUR 40000
4 And the term is 48 months
5 And the interest is 3.7 % p.a.
6 When the contract is calculated
7 Then the monthly installment is 897.80 EUR
As we continue, we find scenarios like the one in Listing 12.3 and many more.
Listing 12.3 Acceptance Test for Alphorn 6, Sentences 3 and 4
Click here to view code image
1 Scenario: Signing a leasing contract
2 Given an offered contract
3 When the customer signs the contract
4 Then the signature date is today
Methods like Specification by Example [ Adzic 2011 ] and collaborative modeling with Example Mapping [ Wynne 2015 ] may help us to find them. As you see, working with scenarios is not necessarily a top-down approach from COARSE-GRAINED to FINE-GRAINED . For instance, when we flesh out the “offering” domain stories with the Alphorn domain experts, they could come up with examples that we had not considered before:
-
A scenario where the customer already has a contract
-
A scenario where the car needs to be preordered
-
And others
Implementing the Domain Model
The choice of programming language and programming paradigm influences how the domain is modeled in code. Good modeling can be done in (almost) every language, though some are better suited and require less “boilerplate code.”
In the following section, we will look at expressing DDD building blocks using object-oriented means. We think this is the most relevant paradigm to our readers’ practice. We will also implement the example in Java, since it is still the most widely used language. After that, we will briefly show how to implement the same domain with functional programming means (with examples in F#). We conclude with a brief consideration of when simpler architectural styles are sufficient.
An Object-Oriented, Domain-Driven Implementation
Domain Storytelling’s pictographic language naturally fits in with the building blocks of DDD’s tactical design:
-
The work objects are candidates for becoming the aggregates , entities , and value objects (implemented as classes or types ) in the domain model.
-
The activities may become the operations (that is, methods , functions , or commands ). Also, the result of an activity can be implemented as a domain event .
Alphorn’s FINE-GRAINED offering stories contain many work objects. One that occurs repeatedly is the contract, so let’s build a type Contract (see Figure 12.5 ). Since a contract has an identity (here explicitly stated with the contract number), we make it an entity .
Figure 12.5 Entity Contract
Interactions with a contract—like filling out, calculating the installment, and signing—turn into methods (see Figure 12.6 ).
Figure 12.6 Entity Contract with methods
Figure 12.7 visualizes the general rule of thumb: “work objects turn into classes, activities turn into methods.”
Figure 12.7 From domain story to class diagram
Other work objects such as installment, price, term, and interest do not have an identity, so we model them accordingly as value objects (see Figure 12.8 ). In this case, the mentioned types also become parameters of the operation calculateInstallment() .
Figure 12.8 Entity Contract with value objects
When digging deeper into the domain, you will see that all operations have preconditions and can be called only in certain states. Expressing these invariants in your code makes it more readable and robust.
If you use test-driven development [ Beck 2000 ], you start coding the domain model by converting our BDD scenarios into executable acceptance tests. Listing 12.4 shows the first Alphorn BDD scenario again.
Listing 12.4 Acceptance Test for Alphorn 6, Sentence 2, with Concrete Values
Click here to view code image
1 Scenario: Calculation of a contract for a midsize car
2 Given a filled out contract
3 And the price is EUR 40000
4 And the term is 48 months
5 And the interest is 3.7 % p.a.
6 When the contract is calculated
7 Then the monthly installment is 897.80 EUR
Listing 12.5 shows an implementation as a JUnit test case.
Listing 12.5 JUnit Implementation of the Acceptance Test for Alphorn 6, Sentence 2
Click here to view code image
1 import org.junit.jupiter.api.Test;
2 import static org.assertj.core.api.Assertions.assertThat;
3
4 @Test
5 void calculateContractForMidsizeCar() {
6 // given
7 var contract = new Contract(
8 Car.of("Volkswagen ID.3"),
9 Amount.of(40000, Currency.EUR));
10
11 // when
12 contract.calculateInstallmentFor(Term.of(48), Interest.of(3.7));
13
14 // then
15 assertThat(contract.installment())
16 .isEqualTo(Amount.of(897.80, Currency.EUR));
17 }
As you can see in Listing 12.5 , line 16, while writing the JUnit test, we have identified two more types: Currency and Amount . (More on that later.)
To make the test run, we need to implement the classes and methods used in the tests. We present only the signatures of the classes and methods here, so as not to go beyond the scope of this book. We start with the entity 3 Contract in Listing 12.6 .
Listing 12.6 Java Implementation of the Entity Contract
Click here to view code image
1 import org.jmolecules.ddd.annotation.Entity;
2
3 @Entity
4 public class Contract {
5
6 public Contract(Car car, Amount price) { /* ... */ }
7
8 public void calculateInstallmentFor(Term term, Interest interest) {
9 /* ... */
10 }
11
12 public Amount installment() { /* ... */ }
13
14 }
Then we add the value objects (see Listing 12.7 ).
3 . In our examples, we use annotation libraries from xMolecules [ xMolecules Website ] to mark which DDD building block a domain model class represents. The Java examples facilitate jMolecules.
Listing 12.7 A Sketch of the Java Implementation of the Value Objets
Click here to view code image
1 import org.jmolecules.ddd.annotation.ValueObject;
2
3 @ValueObject
4 public class Car {
5 public static Car of(String description) { /* ... */ }
6 }
7
8 @ValueObject
9 public enum Currency { EUR, GBP, USD }
10
11 @ValueObject
12 public class Amount {
13 public static Amount of(int amount, Currency currency) { /* ... */ }
14 }
15
16 @ValueObject
17 public class Term {
18 public static Term of(int numberOfMonths) { /* ... */ }
19 }
20
21 @ValueObject
22 public class Interest {
23 public static Interest of(float interestInPercent) { /* ... */ }
24 }
Then, the class Contract is completed with tests for and implementations of the methods offer() and sign () similarly to calculateInstallmentFor() (here omitted for brevity). Interestingly, there is no method fillOut() , although we designed it earlier in the class diagram. Instead, we use the typical Java mechanism for filling out (i.e., creating)—a constructor. This is an example of a programming language influencing the design. There is always a trade-off to be made between (a) expressing the domain in the purest and most “correct” way and (b) not fighting the programming language and writing code that seems “unidiomatic” in that language.
Also, we have not implemented the types Price and Installment sketched earlier (shown in Figure 12.8 ). Instead, we built a single type Amount because both “price” and “installment” are expressed as an amount of money. So, those work objects became names for variables and parameters instead of types.
Earlier, we learned an important business rule from the domain experts: A contract can be signed only if (a) the installment has been calculated and (b) it has not already been signed. To reason about invariants in the bounded context, it is helpful to visualize the life cycle of a contract as a simple state machine, as in Figure 12.9 .
Figure 12.9 Entity Contract as state machine
To express the invariants that we modeled in the state machine, Design by Contract (DbC) is a great help [ Meyer 1997 ]. With DbC, method signatures are extended with pre- and postconditions . Preconditions have to be fulfilled to call the method; postconditions are guaranteed by the method. Unfortunately, DbC is still not supported out of the box in most programming languages (see [ Thomas/Hunt 2020 ]). The Pragmatic Programmers’ recommendation (and ours) is to utilize it as a thinking tool nonetheless.
In languages without built-in support for DbC, one can check pre- and postconditions with assertions [ Evans 2004 ]. Traditionally, preconditions are defined with the keyword require and postconditions with the keyword ensure ; since Java does not support DbC in the language, we have to emulate it here with the keyword assert (see Listing 12.8 ).
Listing 12.8 Java Implementation of the Entity Contract with Assertions
Click here to view code image
1 import org.jmolecules.ddd.annotation.Entity;
2
3 @Entity
4 public class Contract {
5
6 public Contract(Car car, Amount price) { /* ... */ }
7
8 public boolean isCalculated() { /* ... */ }
9
10 public void calculateInstallmentFor(Term term, Interest interest) {
11 /* ... */
12 assert isCalculated() // postcondition
13 }
14
15 public Amount installment() {
16 assert isCalculated(); // precondition
17 /* ... */
18 }
19
20 public boolean isSigned() { /* ... */ }
21
22 public void sign() {
23 assert isCalculated(); // precondition
24 assert !isSigned(); // precondition
25 /* ... */
26 assert isSigned(); // postcondition
27 }
28
29 }
As you can see, we have introduced a new method isCalculated() in Listing 12.8 , line 8, that can be used to define the postcondition of calculateInstallmentFor() (line 12) and the precondition of installment() (line 16). Similarly, we defined the method isSigned() (line 20).
From here on, we “just” need to flesh out the implementation.
A Functional, Domain-Driven Implementation
With the means of a functional language, it is possible to express the domain in an elegant way. The work objects that turn into entities and value objects are implemented as types . Activities are implemented as functions . An implementation of the domain model from earlier in F# might look like in the listings in this section. Let’s start with the value objects in Listing 12.9 . 4
Listing 12.9 F# Implementation of the Value Objects
Click here to view code image
1 open NMolecules.DDD
2
3 [<ValueObject>]
4 type Car = Description of string
5
6 [<ValueObject>]
7 type Currency =
8 | EUR
9 | GBP
10 | USD
11
12 [<ValueObject>]
13 type Amount =
14 {
15 amountValue: int
16 currency: Currency
17 }
18
19 [<ValueObject>]
20 type Term = NumberOfMonths of int
21
22 [<ValueObject>]
23 type Interest = InterestInPercent of float
4 . In the F# examples we make use of nMolecules, the .NET variant of xMolecules [ xMolecules Website ].
We implement the entity Contract as the state machine from Figure 12.9 . Our goal is to use the type system of the programming language to make illegal state unrepresentable [ Wlaschin 2018 ]. We do this by first defining a type for each state, like FilledOutContract and CalculatedContract in Listing 12.10 .
Listing 12.10 F# Types for the States of the Contract
Click here to view code image
1 type FilledOutContract =
2 {
3 number: ContractNumber
4 car: Car
5 price: Amount
6 }
7
8 type CalculatedContract =
9 {
10 number: ContractNumber
11 car: Car
12 price: Amount
13 term: Term
14 interest: Interest
15 installment: Amount
16 }
17
18 type OfferedContract = (* ... *)
19
20 type SignedContract = (* ... *)
To implement Contract itself, we use an algebraic data type (see Listing 12.11 ).
Listing 12.11 F# Implementation of the Entity Contract
Click here to view code image
1 open NMolecules.DDD
2
3 [<Entity>]
4 type Contract =
5 | FilledOut of FilledOutContract
6 | Calculated of CalculatedContract
7 | Offered of OfferedContract
8 | Signed of SignedContract
The activity “The salesperson calculates the installment for the contract” (sentence 2 in Alphorn 6; see Figure 12.3 ) is implemented as function CalculateContract in Listing 12.12 .
Listing 12.12 F# Implementation of CalculateContract
Click here to view code image
1 type CalculateContract =
2 FilledOutContract -> Term -> Interest -> CalculatedContract
3
4 let calculateContract : CalculateContract =
5 fun filledOutContract term interest ->
6 (* ... *)
For the sake of brevity, we will not flesh out the implementation.
If you want to dive deeper into the topic of implementing domain models in a functional style, read Scott Wlaschin’s excellent book Domain Modeling Made Functional [ Wlaschin 2018 ], which has heavily influenced this section.
When a Simpler Style Is Enough
Building a clean, behavior-rich domain model is not always the right choice. The beauty of that design comes at a price. When the price is not justified, building a transaction script, table module, or the like may be appropriate. For example, some parts of a domain may be rather data-centric in nature. In these cases, the behavior is often adequately modeled with create/read/update/delete (CRUD) operations. If this is the case, it does not make sense to invent something that is simply not justified by the domain. CRUD modeling needs not to be bad per se.
Having said that, the more interesting parts of the domain are those that are not data-centric. This is typically the case in what DDD calls the core domain .
What to Read Next?
Now that we have running code in the domain layer, the next step would be to add the surroundings: application layer, user interface layer, and infrastructure layer. That way we develop it into a whole system. However, this book is not about software architecture. If you are interested in an implementation of the Alphorn example with UI and persistence, take a look at the LeasingNinja [ LeasingNinja Website ]. For further reading on how to integrate a domain model into a sound software architecture, we recommend these books:
-
Carola Lilienthal’s Sustainable Software Architecture [ Lilienthal 2019 ]
-
Tom Hombergs’s Get Your Hands Dirty on Clean Architecture [ Hombergs 2019 ]
-
Martin Fowler’s Patterns of Enterprise Application Architecture [ Fowler 2003c ]
For more on domain modeling with OO or FP, read the following:
-
Bertrand Meyer’s Object-Oriented Software Construction [ Meyer 1997 ]
-
Scott Wlaschin’s Domain Modeling Made Functional [ Wlaschin 2018 ]
Finally, two books cover domain modeling and architecture from a DDD point of view:
-
Vaughn Vernon’s Implementing Domain-Driven Design [ Vernon 2013 ]
-
Scott Millet with Nick Tune’s Patterns, Principles, and Practices of Domain-Driven Design [ Millet/Tune 2015 ]
We have now arrived at the code level. When the first iteration is done, let’s start the next one by learning the language ( Chapter 9 ), checking the boundaries ( Chapter 10 ), and working on requirements ( Chapter 11 ) again.
Also, the implementation will influence how the organization does its work, so it can be interesting to see how to support organizational change ( Chapter 13 ).