You are on page 1of 62

Domain Driven Design

Arnaud Bouchez
June 2015
Domain Driven Design (DDD)
 Is DDD good for you?
 Modeling your objects
 Patterns
 Architecture
 practice

Domain Driven Design


June 2015
Domain Driven Design
 Sounds pretty much nice and easy

Domain Driven Design


June 2015
Domain Driven Design

Model-Driven
Design

define identify process express express isolate express state


exclude
model with scope with model with model with model with domain with changes with

Clean/Layered/
Ubiquitous Bounded
Services Entities Value Objects Hexagonal Events RAD
Language Contexts
Architecture

encapsulate with encapsulate with

access with instantiated by Aggregates instantiated by

access with instantiated by

Repositories Factories

Domain Driven Design


June 2015
Domain Driven Design
 Focus on the Domain
 Define Bounded contexts within this domain
 Create an evolving Model of the domain
 Use Ubiquitous Language in model and code
 Identify objects: Values, Entities, Aggregates
 Isolate the domain from other kind of concern
 Publish the domain as well-defined Services
 Integrate the domain services with existing

Domain Driven Design


June 2015
DDD pre-requisites
 Identified and well-bounded domain
 e.g. your business target should be clearly identified
 Access to domain experts
 need iterative creative collaboration
 Skilled team, able to write clean code
 more about code expressiveness than technology
 You want your internal team to accumulate
knowledge of the domain
 therefore, outsourcing may be constrained
to applications, not the core domain

Domain Driven Design


June 2015
Role of Patterns
 In your code: once: it’s a fluke, twice: its
coincidence, three times: it’s a Pattern!
 Discovered (observed), not invented
 Except for their name 
 Elevate effectiveness of our communication
A ‘shorthand’ for more complex ideas

Domain Driven Design


June 2015
DDD: the premise
 Writing software is actually straightforward
 Determining what to write is hard!
 The Key to success is understanding
the Problem Domain intimately
 Not to use the latest shiny technology

Domain Driven Design


June 2015
Check your concerns
 You have a specific problem to solve
 Your goal is identified , but your business is exploring
 You do not know how to accomplish your goal
 You need to bring clarity, and solve inner complexity
 e.g. modeling a lot of rules
 DDD is not to build simple applications – RAD is there
 DDD meets your strategic goals
 DDD is to be used where you will get your business
money, and make you distinctive from your competitors
 You don't have all of these, but at least one or two

Domain Driven Design


June 2015
Domain Driven Design

Model-Driven
Design

define identify process express express isolate express state


exclude
model with scope with model with model with model with domain with changes with

Clean/Layered/
Ubiquitous Bounded
Services Entities Value Objects Hexagonal Events RAD
Language Contexts
Architecture

encapsulate with encapsulate with

access with instantiated by Aggregates instantiated by

access with instantiated by

Repositories Factories

Domain Driven Design


June 2015
Ubiquitous Language
 Developers and Business People
 move in different worlds
 have different languages to express their ideas
 theother 10th kind of people
how do not know about binary…
 use company- or industry-standard terminology

Domain Driven Design


June 2015
Ubiquitous Language
 Developers and Business People

Domain Driven Design


June 2015
Ubiquitous Language
 Language should be Ubiquitous
 Inclasses, methods, variables, even in tests
 Behavior-Driven Development

 Conversing using the same language


 ‘Solutionsmells’ detected by Domain Experts
 Discovery of new domain concepts by developers

 Shared learning by all involved

 Model must evolve: always remove ambiguities

Domain Driven Design


June 2015
Ubiquitous Language
 The best of both worlds

Domain Driven Design


June 2015
Domain Driven Design

Model-Driven
Design

define identify process express express isolate express state


exclude
model with scope with model with model with model with domain with changes with

Clean/Layered/
Ubiquitous Bounded
Services Entities Value Objects Hexagonal Events RAD
Language Contexts
Architecture

encapsulate with encapsulate with

access with instantiated by Aggregates instantiated by

access with instantiated by

Repositories Factories

Domain Driven Design


June 2015
Modeling a Domain
 What do we call Domain here?
 The domain represents a sphere of knowledge,
influence or activity
 As a result
 The domain has to be clearly identified
 Your software is expected to solve a set of
problems related to this domain
 You may have several domains to modelize

Domain Driven Design


June 2015
Modeling
 DDD is some case of Model-Driven Design
 Itspurpose is to create a model
of a given domain
 The code itself will express the model:
as a consequence, any code refactoring means
changing the model, and vice-versa

Domain Driven Design


June 2015
Modeling
 Be honest: reality is just too big
 Modeling is about filtering the reality
for a given use context
 “All models are wrong, some are useful”
G. Box, statistician
 Several models may coexist for a given reality,
depending of the knowledge level involved
 what we call a Bounded Context

Domain Driven Design


June 2015
Modeling
 Bounded Context
 The same reality will appear several times
in several models
 Don't be afraid if the same reality is defined several
times in your domain code, each class for its context
 You need to identify your current model
 Justas in Google Maps the zoom level or the kind of
map shows several models of the same world
 Even models could be abstracted
 This is what DDD does: code abstracts a model

Domain Driven Design


June 2015
Modeling
 Modeling is about forgetting the details
 Focus on the essentials
 Given an objective knowledge level

 Specific to a bounded context

Domain Driven Design


June 2015
Modeling
 Model State
 Static
 To abstract a given state of the reality
 Dynamic
 To abstract how reality evolves (i.e. its behavior)
 Changes are mostly continuous in reality
 Dynamic modeling will create
static snapshots of the reality (called state transitions)
 It will embrace the deterministic nature of computers

Domain Driven Design


June 2015
Modeling
 State brings complexity
 It
is a fact we won’t argue
 So our code should be as stateless as possible

 Some patterns
 Tryto always separate value and time in state
 Reduce statefulness to only the necessary

 Implement your logic as state machines


 instead of blocking code or sessions
 Persistence should handle one-way transactions

Domain Driven Design


June 2015
Modeling
 DDD expresses static model state using
 Immutable Value Objects
 To define a static value
 Entity Objects (or Entities)
 To refer to a given state of given identity
 For instance, the same identity (named "John Doe") may
be, at a given state, single and minor, then, at another
state, married and adult. The model will help to express
the given states, and the state transitions between them
(e.g. John's marriage)

Domain Driven Design


June 2015
Modeling
 DDD expresses dynamic model state
 Via Factory / Repository / Unit Of Work patterns
 Code will get given state of the model
 Then process its domain knowledge
 And return the new state

 Via Events
 When a system does change its state very often
 See Event-Driven Design or Event Sourcing

Domain Driven Design


June 2015
Modeling
 To express the modularity of the model
 Partitioning
 the more your elements have a separated concern,
the better, since the model will be more stateless
 we will create a lot of objects (interface segregation)
 not abuse of inheritance
 are you focusing on the domain, or on your code?
 Grouping
 toexpress constraints, elements may be grouped
 usually, no more than 6/8 elements per diagram
 Aggregate Root to group objects to model constraints

Domain Driven Design


June 2015
Domain Driven Design

Model-Driven
Design

define identify process express express isolate express state


exclude
model with scope with model with model with model with domain with changes with

Clean/Layered/
Ubiquitous Bounded
Services Entities Value Objects Hexagonal Events RAD
Language Contexts
Architecture

encapsulate with encapsulate with

access with instantiated by Aggregates instantiated by

access with instantiated by

Repositories Factories

Domain Driven Design


June 2015
Value Objects and Entities
 Model-level structures
 Reduce the model into objects or structured types
 May be class or record
 Make the implicit explicit
 Naming should follow the Ubiquitous language
 Define dedicated types
 e.g. a TPhoneNumber instead of plain RawUTF8
 Use dynamic structures like TDocVariant
 Especially during initial exploring phase

Domain Driven Design


June 2015
Value Objects and Entities
 Model-level representation will define
 Value Objects
contain attributes (value, size)
but no conceptual identity
 e.g. money bills, or seats in a Rock concert
 Entity objects
are not defined by their attributes (values),
but their thread of continuity, signified by an identity
 e.g.persons, or seats in most planes, as each one is
unique and identified.

Domain Driven Design


June 2015
Value Objects and Entities
 Value objects are immutable by definition
 So should be handled as read-only
 They are incapable of change once they are
created
 Seeking side-effect-free functions
 concept borrowed by DDD to functional languages

Domain Driven Design


June 2015
Value Objects and Entities
 Entities will very likely have an ID field
 To identify a given reality
 To model the thread of continuity of this identity

 But this ID is an implementation detail


 Only used at Persistence Layer level
 At Domain Layer level, data access via an
Aggregate Root, linked to a bounded context
 May be hidden by CQRS statefull services
Query an aggregate, then apply Commands

Domain Driven Design


June 2015
Value Objects and Entities
 Aggregates are a particular case of Entities
 Defined as collection of objects
 nested Values and/or Entities
 That are grouped together by a root Entity
otherwise known as an Aggregate Root
 which scope has been defined by execution context
 Allow composition (or grouping) in the model

 For persistence, are the transactional boundary


 May be NoSQL, or at least via ORM

Domain Driven Design


June 2015
DTO & Events
 Isolate the domain from the outer world
 Value Objects may be used with no translation
 So may be used as DTO classes
 Even Entities may be transmitted directly
 Since their methods should not refer to anything but
their internal properties
 In short: be realistic/lazy, but paranoid
 Better isolate your domain with DTO types
 To increase maintainability and efficiency

Domain Driven Design


June 2015
DTO & Events
 Data Transfer Objects (DTO)
 are transmission objects
 to avoid leaking the Domain objects across the wire
 Anti-CorruptionLayer i.e. separate your layers
 Create gatekeepers that to prevent
non-domain concepts from leaking into your model
 Even public API should use adapters

Domain Driven Design


June 2015
DTO & Events
 Commands and Events
 are some kind of DTO
 since they communicate data about an event
and they themselves encapsulate no behavior
 in mORMot, interface types e.g. over Websockets
or via master/slave replication of simple tables

Domain Driven Design


June 2015
Factory & Repository
 Factory pattern
 is used to create class instances
 In strongly-typed OOP (like in Delphi, Java or C#),
this pattern is in fact its constructor method and
associated class type definition, which will define a
fixed set of properties and methods at compilation
 not as e.g. in JavaScript or most other script languages
 is used to create interface instances
 see SOLID principles (mainly Liskov substitution)

Domain Driven Design


June 2015
Factory & Repository
 Repository pattern
 used to save and dispense each Aggregate Root
 Can use e.g. TSQLRecord “Layer Supertype”
 ORM / CRUD interface
 Or dedicated repository classes
 Dedicated interfaces (may be CQRS but not anemic)
 Following Ubiquitous domain language (not CRUD pattern)
 Saving data is a concern orthogonal to the model
 DDD architects claim that
persistence is infrastructure, not domain
 Domain layer should be abstracted (via IoC)

Domain Driven Design


June 2015
Domain Driven Design

Model-Driven
Design

define identify process express express isolate express state


exclude
model with scope with model with model with model with domain with changes with

Clean/Layered/
Ubiquitous Bounded
Services Entities Value Objects Hexagonal Events RAD
Language Contexts
Architecture

encapsulate with encapsulate with

access with instantiated by Aggregates instantiated by

access with instantiated by

Repositories Factories

Domain Driven Design


June 2015
Services
 Aggregate roots’ methods
 Aggregate roots are the only kind of entities
to which your software may hold a reference
 Tend to be the main access point of any process
 from the application layer point of view
 Often end up as state machines
 with all their methods
 Itcould be handy to
publish those methods as stateless Services
isolated at Application layer level

Domain Driven Design


June 2015
Services
 Domain services
 are used to model primary operations
 i.e. publish tools for modeling processes
 that do not have an identity or life-cycle in your domain
 that is, that are not linked to one particular aggregate root,
perhaps none, or several
 In this terminology, services are not tied to a particular
person, place, or thing in my application, but tend to
embody processes
 Main rule is to let the Domain layer focus on the
business logic

Domain Driven Design


June 2015
Services
 Domain services
 They tend to be named after verbs or business
activities that domain experts introduce into
Ubiquitous Language
 They should be exposed as dedicated client-oriented
methods
 Following Interface segregation principle
 Do not leak your domain! Develop your Application layer
services directly from the needs of your client applications,
 Main rule is to let the Domain layer focus on the
business logic

Domain Driven Design


June 2015
Services
 Unit Of Work
 Can be used to maintain a list of objects affected by
a business transaction
 Coordinates the writing out of changes and the
resolution of concurrency problems
 Persistence Ignorance or Database agnosticism
 At application layer level
 Implements transactions for Domain entities and services
 May be implemented by ORM to “hydrate” Aggregate roots
class instances as abstractly as possible

Domain Driven Design


June 2015
Domain Driven Design

Model-Driven
Design

define identify process express express isolate express state


exclude
model with scope with model with model with model with domain with changes with

Clean/Layered/
Ubiquitous Bounded
Services Entities Value Objects Hexagonal Events RAD
Language Contexts
Architecture

encapsulate with encapsulate with

access with instantiated by Aggregates instantiated by

access with instantiated by

Repositories Factories

Domain Driven Design


June 2015
Clean / Layered Architecture
 DDD 4-tier layered architecture
 Presentation Layer
 Application Layer
 Domain Layer
 Business Layer
 and cross-cutting / vertical layer

 With proper isolation of the Domain layer


 To focus on the domain
 To not let the domain be polluted
 by technical stuff, application particularities…

Domain Driven Design


June 2015
DDD n-Tier Architecture

Domain Driven Design


June 2015
Clean DDD architecture
 From the physical point of view
 N-layered DDD architecture
Layer Description

Presentation MVC UI generation and reporting

Application Services and high-level adapters


Domain Model Where business logic remains
Data persistence ORM and external services

Cross-Cutting Horizontal aspects shared by other layers

Domain Driven Design


June 2015
Clean DDD architecture
 From the physical point of view
 Stilllooks like a classic 4-tier layered design
 But DDD does its best
to isolate the Domain Model
from any dependency
 Abstractfrom technical details
 Do not be tied to the application layer

 To modelize a “clean” architecture

Domain Driven Design


June 2015
Technical
Implementations

Web Rich Fake Mocks DB Web File


AJAX Client Datasets Stubs ORM Services System

User Interface Behavior Tests Infrastructure

exposes validate implements


Application
Services

Workflows

get/save use
execute
objects objects
Domain
Services
Domain
Model
Third Party Repository Domain
Unit Tests
Interfaces Interfaces Interfaces

Aggregates

Entities

Value
Objects

Domain Driven Design


June 2015
Clean DDD architecture
 From the logical point view
 Onion-likemore than layered-like
 Domain at the core
 Should stay as stable as possible
 Stay as uncoupled as possible
 Define domain objects
 Value Objects, Entities, Aggregate Roots
 Define domain services consumed outside
 Define abstract services implemented outside
 e.g. persistence interface

Domain Driven Design


June 2015
Clean DDD architecture
 From the logical point view
 Onion-like more than layered-like
 Application services layer
 Willchange very often and evolve a lot
 Typical workflow:
 Dehydrate Aggregate Roots using persistence service
 Call the Domain services
 Call external services, commit persistence (Unit of work)

Domain Driven Design


June 2015
Clean DDD architecture
 From the logical point view
 Onion-like more than layered-like
 Presentation services layer
 Foreach end-user application
 Depending on each technology (VCL, HTML, AJAX)

 Infrastructure services layer


 Persistence depending on database (SQL/NoSQL)
 External services (SOA)

 Tests with stubs and mocks


 Regression and integration tests are part of the design

Domain Driven Design


June 2015
Clean DDD architecture
 Clean, since it controls coupling
 Coupling is toward the center
 Allcode can depend on layers more central
 But cannot depend on layers further out from the core
 This architecture is unashamedly biased toward OOP,
which puts objects before all others
 Relies on the Dependency Inversion principle
 Uses interface for behavior contract
 Force the externalization of infrastructure

Domain Driven Design


June 2015
Clean DDD architecture
 Clean, since it is upside-down
 Database is not the center of your logic
 Nor the bottom of your physical design

 Database is external
 There is no such “database application” in DDD
 As any other third-party service

Domain Driven Design


June 2015
Technical
Implementations

Web Rich Fake Mocks DB Web File


AJAX Client Datasets Stubs ORM Services System

User Interface Behavior Tests Infrastructure

exposes validate implements


Application
Services

Workflows

get/save use
execute
objects objects
Domain
Services
Domain
Model
Third Party Repository Domain
Unit Tests
Interfaces Interfaces Interfaces

Aggregates

Entities

Value
Objects

Domain Driven Design


June 2015
DDD commitments
 I shall collaborate with domain experts
 I shall focus on using our ubiquitous language
 I shall not care about technical stuff or framework,
but about modeling the Domain
 I shall make the implicit explicit
 I shall use end-user scenarios to get real and concrete
 I shall not be afraid of defining one model per context
 I shall focus on my Core Domain
 I shall let my Domain code be uncoupled from any external
influence
 I shall separate values and time in state
 I shall reduce statefulness to only the necessary
 I shall always adapt my model as soon as possible,
once it appears inadequate

Domain Driven Design


June 2015
DDD & mORMot

Domain Driven Design


June 2015
DDD & mORMot
 DDD may be implemented with mORMot
 Value objects
 as record and dynamic arrays
 or TSynPersistent / TSynAutoCreateField class

 Entities (and Aggregate Roots)


 as TSynAutoCreateField class
and mORMotDDD.pas TDDDRepositoryRestFactory
 or directly – but not preferred – as TSQLRecord
 Data Transfer Objects as record or TDocVariant
 Depending if the schema is fixed or variable

Domain Driven Design


June 2015
DDD & mORMot
 DDD may be implemented with mORMot
 Services as interface-based services
 At Domain or Application layer
 To be accessed locally or remotely
 Security, Asynchronous Callbacks (Websockets)

 Services as method-based services


 At Domain layer, for Aggregate root methods
 At Application layer, for publishing REST services

Domain Driven Design


June 2015
DDD & mORMot
 DDD may be implemented with mORMot
 Persistence as TSQLRest or dedicated service
 WithTSQLRestBatch as Unit-Of-Work
 Advanced mapping via mORMotDDD.pas
TDDDRepositoryRestFactory
 Command Query Segregation Services (CQRS)
 mORMotDDD.pas ICQRSQuery ICQRSCommand
 Dual-phase commit for SOA orchestration

Domain Driven Design


June 2015
DDD & mORMot
 DDD may be implemented with mORMot
 Desktop Applications User Interface
 With optional auto-generation of the layout
 Including grids, i18n and interaction with the VCL

 Web Applications User Interface


 AJAX over REST/SOA
 Web using MVC/Mustache

 Code-driven reporting
 Data from ORM/SOA objects, not TDataSet
 Integrated preview and PDF export

Domain Driven Design


June 2015
DDD & mORMot
 DDD may be implemented with mORMot
 Services/daemons abstract classes
 Thread-based or process-based daemons
 Integration as Windows Services or Linux Daemons
 Settings, console, monitoring, remote administration

 All cross-cutting features are available


 Filtering/validating,
security, cache, logging
 JSON, transmission, RTTI, tests, stubs/mocks

Domain Driven Design


June 2015
Presentation

AJAX Reporting UI

REST Client i18n

HTTP 1.1

Application

REST Server

Domain
Model

Services
(interface-based)

Entities Aggregates Value Objects


as TSQLRecord as TSQLRecord as record

Data persistence

ORM

Cross-Cutting

Security Tests Filtering


Cache Logging SQLite3
Sessions Mocks/Stubs Validation

External DB

Domain Driven Design


June 2015
Domain Driven Design
Arnaud Bouchez
June 2015

You might also like