Sunteți pe pagina 1din 9

Domain Driven Design pulls down the

wall between mental model and


executable code
by Roland Koer, rkoer@bwin.org

January 28, 2008

Software is more than often not a valuable asset in your strategic port-

folio: the implementation works that's true, but can you adapt its intrinsic

business concepts easily to meet the changing requirements you face? Did

your business analysts and your developers take the opportunity to elaborate

an abstraction of your business with formal elegance and cognitive depth,

thus creating a common ontology about the core concepts of your business?

Further, does the implementation of your core business reect these well un-

derstood concepts so that the code is structured along the boundaries of

these concepts and they are isolated and therefore exchangeable when the

need arises?

Object Oriented Analysis and Design provides well suited instruments to

transform your software black box into a central intellectual asset, that pro-

vides (1) an ubiquitous language about the topics and relationships in your

business, shared among business and development departments and (2) aug-

ments therefore the reasoning about core concepts not only for implementers

but more important for decision makers. In fact their mental model is re-

ected in the constructs of the software implementation et vice versa. There-

fore I would consider Domain Driven Design as a knowledge management

instrument.

1
When Software becomes hard
Inexible, incomprehensible and therefore unmaintainable code is still rather common in

our days. If we divide software implementation into (1) technical infastructure including

databases access, service integration, communication interfaces, installation requirements

etc. and (2) business concepts we experience most often that the developers have to strug-

gle hard with the rst, so that the latter suers. When the requirements provided by the

business analysts are not examined with verve to nd commonalitys, generalisations and

not ovious but - once discovered - powerfull methapors, software development is infras-

tructure focused. Technophile software. Developers learn that a certain library or API,

a certian framework or persistence technology would make the software better, again

pushing the focus further away from the problem domain. The intellectual gap between

developers and business increases, instead of a common language able to describe the ex-

isting and executable model, our business analysts can only guess about the mechanics at

work in the product, while the developers must work around increasing obstacles to fulll

further requirements: the at rst hand poorly reected domain contours never t and

work-a-round after work-a-round, from exceptional case to exception-of-the-exception,

the business logic complexity grows whidening the gap of missinterpretation.

Modelling with Cognitive Depth


A Domain Model is a generalised, abstracted and conceptual description of a problem's

solution. In its executable form it solves domain-related problems for the user, as code

therefore is the logic-core of the software, surrounded merely by infrastructure. The goal

of domain modelling is to reect a business with deep cognitive resolution. By identifying

the underlying concepts of the problem domain and shaping a Ubiquitous Language a

domain expert and a software architect achieve a common understanding of the business

domain. They can argue in this precise jargon in faith that the concepts embodied in the

software reect precisely what they are talking about. Designing software here means

to carry out a discourse about the concepts and their relationships between each others.

In a continuous iteration of renement a knowledge-rich Deep Model of the problem

domain will be shaped and carved out.

2
Domain Driven Design as a Modelling Methodology
Domain Driven Design1 provides a unied theory on how to implement a Domain

Model based software stack. A Domain Model is embedded in a layered architecture

consisting of an (1) interface layer towards the external world accessing (2) an application

layer conceived to orchestrate the operation of a certain user role on the (3) domain

model, which in turn uses an (4) infrastructure layer to access resources. The division

into application layer and domain model may raise your attention; both represent what

a software engineer would call  business logic but the dierence is crucial to understand

the power of domain modelling. The model embodies its underlying domain as a set of

concepts and their relationships. But a concrete user role needs to access this model

from its own perspective, therefore an application represents a user role that operates

the model in a concrete business context: e.g. in a web-shop, a customer application is

for buying items and a supplier application is for delivering items to the inventory. This

is what Trygve Reenskaug named Model View Controller.

Object Oriented Design as basis of a Domain Model


Ole-Johan Dahl and Kristen Nygaard developed the concepts of Object Oriented Pro-

gramming at the Norwegian Computing Centre from 1961 to 1967. The approach gained

immense success in the mid-1990s, so that today Object Orientation can be considered

as the broadest adopted programming paradigm in the software industry. The crucial

dierence to other paradigms lies in the encapsulation of data and functionality in a

component entitled as Object. Each Object knows the data and the behaviour of the

concept it represents. This principle is called behavioural completeness which is

familiar to the notion of encapsulation. In  Naked Objects By Richard Pawson and

Robert Matthews
2 the Authors state about encapsulation:

[. . . ] The word has two meanings in English. The rst has to do with being

sealed, as in a medicinal capsule [. . . ]. The second meaning of encapsulation

is that something exemplies the essential features of something else, as in

'this document encapsulates our marketing strategy'. This second meaning -

which corresponds to the principle of behavioural completeness - is far more

important in the context of object-oriented modelling.

1
not to be confused with Model Driven Design and Model Driven Architecture (MDA)
2
http://www.nakedobjects.org/book/section5.html

3
Domain Driven Design embraces the idea of behavioural completeness more

than any other approaches in Object Oriented Design such as Component Ori-

entation (as in EJB) or the Transaction Script Pattern

Antagonists
Several concurrent approaches exist to Domain Models. They are not always hundred

percent contradictory to DM, but are often used not as a complement but as substitution.

Component Orientation
Its goal is to creating plug-and-play reusability and most often a distributed architecture.

When can a developer benet best from such components? When there is a need to ab-

stract away underlying technical specialities, thus making them interchangeable and easy

to use. In fact we experience a common usage of components in database access, message

queuing and mail server access. The usage of component oriented business logic was in

fashion in the earlier 2000ths mainly due Enterprise Java Beans. In the following

EJB's have been widely criticised for the complexity burden an implementator has to

carry. Writing reusable components as business objects bear a lot of eort because the

problem domains most often contain contradictory forces and specialities of the business

case. The focus on infrastructure concerns - reusable entities and distribution  doesn't

help with resolving pure conceptual problems faced in the business domain. A component

oriented approach will not provide the cognitive richness of a true Domain Model.

Inversion of Control Containers


The Idea of Dependency Injection is not totally contradictory to Domain Mod-

elling, but often a Factory Method in an Aggregate represents an important

domain concept, therefore building a Domain Model via IoC should be done merely

for infrastructure and services.

Business Process Orientation


Process Orientation has its roots in business management, namely Michael Porters Value

Chain [porter85] The process focuses on its result, making it explicit in a sequential or-

der how it can be achieved. This Idea is very compelling for a software developer, but

you have to notice that the businesses that t into the value chain metaphor are getting

lesser and lesser. Charles Stabell and Oystein Fjeldstadt [Stabell98 propose therefore

4
two complementary concepts: (1) the Value Shop and (2) the Value Network. In a

Value Shop no sequential xed set of activities or resources, but each problem treated

uniquely is used to create value. The Domain Model approach, being not tied to a

certain structure like sequence for processes is perfectly suitable to implement a Value

Shop. Value Networks are complex sets of social and technical resources. They work

together via relationships to create economic value. As you can see easily this is what

SOA is for, while a specic SOA resource could rely on a Domain Model.

Integration into Development Processes


Domain Driven Design ts well into almost any development process. For agile methods

it should be remarked that a Domain Model will not arise from small refactorings but

from an intense design phase with business experts. The continuous refactoring in the

very iteration cycle solves design mistakes and optimizes towards a local maximum, a

Deep Model will not be a by-product of such optimization since it requires attention

to conceptual contradictions over the whole system. But embracing iterative Modelling

and refactoring the Model subsequently in dedicated design sessions will sustain changing

requirements and deeper insight.

The Case Study


A well known story: The business analysts came to the insight that a web-shop is needed

as soon as possible. They organized a big team and generous resources, hired a scrum

master and started fast and made quick progress. They delivered nearly exactly at

estimated release date and the shop was a big success. Now that the developers had time

to take a deep breath, everyone agreed that the code is unbearable: long methods with

multiple implicit concepts sprinkled and entangled all over the code-base. The team lost

a lot of speed in the last iterations and had a lot of trouble to nd bugs. At this point

it was easy to take the opportunity to prototype a domain model to show the validity

of the approach and compare it to the existing solution since the business requirements

where well understood.

A Shopping Order
In the web-shop several kinds of product can be ordered: the Virtual Products

subsum (1) tournament tickets, sweepstakes and real money - these are inmaterial and the

shipping of these products consist only of the transfer of bytes and (2) physical products

5
which are stored in a warehouse and shipped via paket delivery services. Several existing

services have to be integrated; the sweepstake service and the tournament service allow

an the ordering of a single item at once, the warehouse service is supposed to handle

all physical items of an order together since they should be shipped as whole to reduce

shipping costs. We note a twofold way of ordering items correlated to the notion of Deep

physicalness of items. But we can argue that a single-item-at-once strategy seen in Model

the immaterial ordering is not a necessary property attributable to immateriality - its

perfectly feasable that such an item is ordered in a bunch with others. In our case

its the behaviour of the given services that forces us to such a distinction. In fact the

service contracts says these services should be called singularly until a order fails, then

no item of the given type should be ordered anymore. This deeper insight leads us

to a Conceptual Contour where we can attribute a Strategy to every Product

Type: (1) sweepstakes, tournament ticket and realmoney follow Order Until Failure

Process while (2) physical products use Whole Order Process.

Figure 1: The Order consists of several Order Parts, each of it linked to a dened
Order Process

The identied Product Types need to be ordered through their associated services

therefore it makes sense to split the Order in parts so that items of the same Product

Type are ordered in a distinguised time slot. When speaking of physical product this is

enforced by the domain because shipping a single paket is desirable, but for the others

its mere convention: nothing in the problem domain or in the services contracts tells us

that we need to follow this contour. Wen we decide to aggregate the ordering for same

product types, we need to gather all the products of same type and order them with the

given Order Process. An argument for doing so comes from a pure design perspective: Supple

by having several Order Parts, each encapsulating a single service, we can associate Design

6
them with knowledge about what items they want to order. The decision which item to

order is local to the single Order Part, the what and the how in one Class are aiming

for Behavioral Completiness allowing a easy extention of the order process.

An overview of the Order Process environment


Dening a model just for the order itself is not enough since this model needs to interact

with other concepts. In the case study the order derives from a shopping cart. What are

the concepts which surrounds the Order Process? A discourse of the Ubiquitous

Language should reveal the contours and mechanics of this surrounding environment.

The Shopping Cart is a rst methapor for our Language Discourse. Whats a

Shopping Cart for? collecting items and for (2) ordering those
It could be for (1)

items ; we know also that we have to (3) calculate the prices attributed to each item,
since it can be bought in bonus points and money and (4) we have to calculate the

shipping costs and nally (5) send a receipt. As one can see from this description a
Shopping Cart has many responsibilities: by decomposing them we can nd a more

precise language and the Conceptual Contours of our model. The rst activity is

collecting items, in fact we need a Shopping List of all items a customer wants to buy.

Since this list can be persisted over weeks before a customer nally commits the order,

we need to recalculate the prices every time the cart is shown - given the points and

money in customers current account. A Checkout Plan therefore has a temporary

price attribution to every Shopping List item, plus the shipping costs and contains

now all the information to allow the order. After the order a Receipt should show the

success of every item sent to the customer.

Gains and Obstacles


Beautiful Evidence
When modeling the order process Design Patterns popped up like natural properties,

oh this is a Strategy, oh this is a Factory Method! I was able to justify their

adoption through the innate concepts of the domain or sometimes by a supple congruence
3
in design . It all assembled to a complete picture of what an order process looks like,

3
Many Design Patterns must be seen as mere work-a-rounds for poor language features.
For example a Visitor is a Double Dispatch solution for languages which lack Multi
Method support. A Command can be seen as a x for the lack of Closures (see
http://c2.com/cgi/wiki?AreDesignPatternsMissingLanguageFeatures). Although Domain Driven
Design builds a model of an abstract concept, the tools with which we build that model are never ab-
stract: a concrete language, a concrete deployment scenario, a concrete scale of usage has to be taken
into account. Therfore also the weaknesses of a language and the commonly adopted workarounds

7
resembling a executable model of a mechanical machine. The beauty one experience best

is when nothing can be subtracted to the model, without that this feature is missing and

nothing - justied by the inherent mechanics of the model- can be added. To achieve

this golden mean should be the goal of any modeling.

Ubiquitous Language
The discover of a precise jargon led to a better understanding of the problem domain

itself. Questioning the obvious methapor of the Shopping Cart issued a cascade of

insights and new contours with clearly distinguished responsibilities arouse. The Ubiq-

uitous Language is fundamental for all further knowledge crunching, it provides the

intellectual material for reasoning toward a deeper model. Choose a clear and easy

language, but never a dull, buzzwordy one, nouns like Service, Provider, Service-

Provider, Manager should raise your eyebrow.

Extensibility
With clear separations of concepts, exchangeability and extensibility of the model is not

far. If the Conceptual Contour is well chosen, the parts which need to be changed,

form a local and logical unit, a modication of an implicit algorithm is not needed,

while the extention of the unit is supported. When presenting the model, I was able

to introduce a new Product and a new Order Part quickly by creating specialized

classes without aecting other logic.

Diculties
To nd a common language is hard enough. Sharing a Deep Model with new people seems

a constant challenge, often implementers have a very technical point of view so that a

conceptual approach creates serious disturbance. Its not easy to shift the debate away

from infrastructure issues. Its not really a domain model when it has no OR-Mapper?

Its not a Domain Model when its not done in UML? Awareness for the conceptual view

is the most important lesson I have learned from DDD. This is also the main reason I

wrote this text, to advocate a more intelligent way of inventing software.

are building blocks of the model in the same way as performance bottlenecks will inuence the
architectural decisions in the model!

8
Appendix
Further Readings
Domain-Driven Design: Tackling Complexity in the Heart of Software by Eric Evans,

Publisher: Addison-Wesley; ISBN: 0-321-12521-5

Thanks
Klaus Horsten, Martin Kügler, Josef Scherer, Hannes Stockner, Jakob Stemberger for all

the discussions

S-ar putea să vă placă și