Prague, 18-19 October 2018
Domain-Driven Design
Beyond the infamous
repository pattern
Cyrille Martraire
@cyriux
Once upon a time
2001
DAO
With DTO
And DAO Factory!
But now we got better…
8
2003
DAO
Repository
DAO
Generic Repository
DDD
NOT!
So what is DDD?
Passionate
developer
PARIS
Since 1999
@cyriux
Cyrille Martraire
Paris Software Crafters
Community
http://www.meetup.com/paris-software-craftsmanship/
TDD
BDD
DDD
Legacy
DDD?
h#p://www.virtual-genius.com/blog/post/Domain-Driven-Design-Immersion-Course-e28093-Part-5.aspx
Seniors	Developers
h#p://www.thisisio.ie/blog/arDcle/149/hiring_senior_developer
OFTENMISTAKEN
No Tool Needed
CQRS: most popular
WELL-respected
@yanaga
@zpapierski
@@mtnygard
My DDD Map
29
Modeling == Code
Strategic Design
Bounded Context
Context Mapping
CQRS / EC
large-scale structures
Tactical Design
Value Object
Entities
Repository
Aggregate
(patterns)
Domain Events
Focus on Core Domain
Ubiquitous Language
(BDD)
Hexagonal Architecture
FP + OO style
Immutable
Side-Effect-Free
Patterns
Monoids
Bubble Context & Legacy
Emerging Design
DDD Map
30
Modeling == Code
Strategic Design
Bounded Context
Context Mapping
CQRS / EC
large-scale structures
Tactical Design
Value Object
Entities
Repository
Aggregate
(patterns)
Domain Events
Focus on Core Domain
Ubiquitous Language
(BDD)
Hexagonal Architecture
FP + OO style
Immutable
Side-Effect-Free
Patterns
Monoids
Bubble Context & Legacy
Emerging Design
DDD Essentials
Curious about the domain
Talking the Domain Language
Focus on Core Domain
Modeling == Code
Strategic Design
(+ techniques to achieve that)
31
Example
PLZ!
Domain Experts!
Please add a
discount code to the
purchase!
You mean the
shopping cart?
Yes, this is what I
meant
(of course)
Ok, so let’s add a
voucher field to the
class ”BasketModel”
Purchase
Shopping Cart
BasketModel
39
problem
Systematic
Translation
(waste of time + confusion as-a-service)
solution
Ubiquitous
Language
talk the domain language
Ubiquitous Language
• Naming
•Searchable
•Easy to pronounce
•No abbreviation
• Definitions
•Shared definition
•Understand, not just a vocabulary
h#p://www.visualdicDonaryonline.com/house/structure-house/stairs.php
Everyone
talking the
Domain Language
44
Everyone
talking the
Domain Language
Everywhere
45
Everyone
talking the
Domain Language
Everywhere
(even in the code)
46
90%
Business
Domain
Language
here
Extract a word cloud
from your code BAD
Extract a word cloud
from your code Better
null
DDD style of code?
• No technical pollu5on	
• Spring,	Hibernate,	logger	
• javax.*	
• SQL
[Object Calisthenics]
1. Wrap all primitives and strings
2. Use only one dot per line
3. Don’t abbreviate
4. Keep all classes small
5. Don’t use any classes with more
than two instance variables
6. Use first-class collections
7. Don’t use any getters/setters/
properties
Ubiquitous Language
everywhere
52
So you mean
DDD is primarily just
talking business
domain?
53
Ubiquitous Language
everywhere
55
https://leanpub.com/livingdocumentation
BUY MY BOOK!
When to apply DDD?
57
WeWant:
WeWant:
Anapptodetect
paymentfrauds
Rich business domain
60
Risk is in the domain
Apply DDD!
61
WeWant:
Afeaturetobeatour
competition
Differentiating business
domain
63
Value is in the domain
Apply DDD!
64
WeWant:
AnotherTODOlistapp
Go CRUD!
66
Focus on the
Core Domain
67
Differentiating to
the business?
Apply DDD!
69
Not differentiating?
BUY
Domain
Curiosity
72
I only care about
Kubernetes
Hey!
Finance
is cool!
Oh, this
domain is
really cool!
Oh, this
domain is
really cool!
I’d like to
know it
better!
Start with
Examples
79
Scenarios
Intent
Scenarios
Concrete examples
BDD: probably your best
friend to start DDD
Domain
Language
(you can be dogmatic on that)
Modeling == Code
85
Example
PLZ!
*NOT* UML!
h#p://depinfo.u-cergy.fr/projets/close2u/fr/tag/uml/
Kitten kitty = new Kitten(Attitude.ROCK_STAR);
Microphone mike = new Microphone();
kitty.sing(mike);
system.out.println(mike.playBack());
//”mew mew meeew”
Good modeling?
91
Learn the business domain
by reading the code
92
Learn the business domain
by reading the code
93
and running the code
Domain
Modeling
(invest where it matters)
HOW?
Domain modeling toolbox
(not the important stuff)
96
Tactical Patterns
97
3 kinds of classes:
Value Objects
Entities
Services
98
Equality by value
Value Object
« DayShi= by -2
WORKING days »
No geGer/seGer
Immutable
Value Object
Behavior!
Perfect Value Objects:
Java Enums
Scala Case Classes
Arbitrary	IdenDty	
NoDon	of	conDnuity	
over	Dme
Entities
Not	a	value	
Not	an	enDty	
”Giving the illusion of an
in-memory collec6on”
Domain Services
h#p://www.andeka.co.cc/2011/07/postbox-251.html
Repository
h#p://www.andeka.co.cc/2011/07/postbox-251.html
Interface
DAO
Repository
h#p://www.andeka.co.cc/2011/07/postbox-251.html
Catalog
ItemListDAO
Repository
h#p://www.andeka.co.cc/2011/07/postbox-251.html
Catalog
ItemListDAO
Domain Language
Implementation
Language
Persistence Ignorance
•You	can	oYen	defer	decisions	about	
persistence		
•Your	domain	must not care
Repository
Strategic Design
112
Strategic
Design(usefull all the time)
Bounded Contexts
Explicitly define the context within which a model
applies. Explicitly set boundaries in terms of team
organization, usage within specific parts of the
application, and physical manifestations such as code
bases and database schemas. Keep the model strictly
consistent within these bounds, but don’t be distracted
or confused by issues outside.
Bounded Contexts
Explicitly define the context within which a model
applies. Explicitly set boundaries in terms of team
organization, usage within specific parts of the
application, and physical manifestations such as code
bases and database schemas. Keep the model strictly
consistent within these bounds, but don’t be distracted
or confused by issues outside.
Example
PLZ!
Please add a new
discount mode
Where do I add that?
I know: I’ll add
the code in the
MainController
class!
MainController
28 fields here
…
245 methods here
…
6422 lines
problem
Code Gravity
big stuff attracts even more stuff and gets bigger
@carlopescio
solution
Domain
Boundariesbusiness domain as code modules, literally
Payment
…
Discounting
…
Add the
feature
only here
Refactor based on your
domain understanding
124
Domain-Driven
Refactoring
125
We want IT
alignment blabla…
We want IT
alignment blabla…
I know how to do
that!
Once you know DDD…
Functional Area
|
Code Module
130
1-to-1
Pre-NegotiationListing)
B2BOrdering
Fraud
Détection
Payment
Sourcing
Distribution
Rates	Grid
RealTime
Prices
Gift Cards
Content &
Comparators
Sales
Promotion
Acquisition
TV	Campaigns	
Online	Ads
Company	
Rating	
Product	Reviews
Shopping Cart
Catalogue
Search
Categories
Tags
PartnershipsSecondary
Listing
Internal
Purchasing
Rates
CrossSales Navigation
SEO
Marketing
Customer
addressLine
zipcode
city
…
Hey!
Companies have a
different billing
address!
I know: let’s add it
with a flag!
Purchase
addressLine
zipcode
city
has2AddressesFlag
addressLine2
zipcode2
city2
Customer
addressLine
zipcode
city
has2AddressesFlag
addressLine2
zipcode2
city2
If (! has2AddressesFlag)
billing address line = …
billing zip code =
billing city =
else
billing address line = …
billing zip code =
billing city =
Customer
addressLine
zipcode
city
has2AddressesFlag
addressLine2
zipcode2
city2
If (! has2AddressesFlag)
billing address line = …
billing zip code =
billing city =
else
billing address line = …
billing zip code =
billing city =
Everywhere
problem
Code Mess
by lack of domain understanding
solution
Bounded
Contexts
split 1 big model by sub-domains
Split by business domains
141
Customer
addressLine
zipcode
city
date
amount
user
Account
addressLine
zipcode
city
Recipient
+
+
Shipping
BillingShopping Cart
Shipping
BillingShopping Cart
Shipping
BillingShopping Cart
Bounded Contexts
by domain
Customer
addressLine
zipcode
city
date
amount
user
Account
addressLine
zipcode
city
Recipient
+
+
New names
customer
≠
account
≠
recipient
146
Near Synonyms
Customer
addressLine
zipcode
city
date
amount
user
Account
addressLine
zipcode
city
Recipient
+
+
Suggest Contexts
Customer
addressLine
zipcode
city
date
amount
user
Account
addressLine
zipcode
city
Recipient
+
+
Default value:
billing address =
shipping address
But… that’s
massive duplication!
”No Duplication”
means ”Coupling”
Evolve differently in the
long term
151
addressLine
zipcode
city
Account
Billing
addressLine
zipcode
city
Recipient
Shipping
addressLine
zipcode
city
postbox
Account
Billing
addressLine
zipcode
city
Recipient
Shipping
addressLine
zipcode
city
postbox
Account
Billing
addressLine
zipcode
city
doorCode
Recipient
Shipping
Purchase BillingUnit
DeliveryRequest
*
*
e.g. marketplace
What is a book at Amazon?
•Catalog: Picture, title, authors, rating, format
(ebook or paper), category
•Recommandation: List of books often bought
together with it
•Shipping: Dimensions, weight, international
restrictions due to content
•Shopping cart: Price, discount eligible
•Customer review: List of (rating, review,
review rating)
•Book Search: title, isbn, authors
•Search Inside!: full-text content, copyright-
dealing policy
Different perspectives
My book is not your book
Fragmenting your model
Separate models = simpler than single model
@zpapierski
Conflicting views
suggest several contexts
“I don’t need all these data for my
use-case, I just need these 3 fields”
Polyglot persistence (random
examples)
•Catalog: NoSQL
•Recommandation: Batch + GraphDB
•Shipping: RDBMS
•Shopping cart: RDBMS
•Customer review: Cassandra
•Book Search: Elastic Search
•Search Inside!: Redis + CDN
Team organization
•Catalog: Team 1
•Recommandation: Team 2
•Shipping: Team 3
•Shopping cart: Team 4
•Customer review: Team 5
•Book Search: Team 6
•Search Inside!: Team 7
— @zpapierski
by the way...
loosely-coupled,
service-oriented
architecture with
bounded context.
loosely-coupled,
service-oriented
architecture with
bounded context.
Adrian Cockcroft
Microservices!
DDD Framework?
DDD Framework?
What language?
What language?
Does not matter
(but easier with F#)
Is DDD for you?
• Do you feel close to XP?
• Do you love distributed caches?
How to go further?
Read the blue book
Read Martin Fowler
Try Event Storming
h#p://cathy313.centerblog.net/539-bisounours
Micro-Services
+
Event-Driven
Architecture
Micro-Services
WHY microservices?
INDEPENDENT Work Streams
GRANULAR Independent Deployments
Plus recent history has proven we don’t
have the DECOUPLING discipline
FAULT-isolation
Partioning by domains
Partioning	the	world	into	interconnected	platforms	
of	services	partitioned	by	business	sub-domains
185
Sub-Domains
Init
CP purpose &
EC Date
Team &
Collaboration
StrucKyc
FATCA
Embargo
Bundle
Limit
Check
Integration
Risk
Sharing
Federation
Pricing
Integration
CO
IFRS9
classification
Volcker
classification
Mandate
NDA
internal
billing
PoA
AML
Liq
Integration
Legal
Blacklist
Hedging
Approval
Pre
KyC
Closing
Prospects
Ref
WH Tax,
Margin,
Fees
tags: ReadModel, WriteModel,
Projection, Service, BFF, Infra
Microservices in practice
Each microservice has its own private logical ”database”:
CREATE DATABASE microservicename;
Microservices expose API’s and consume other services
http / REST / Json
Most microservices are built on a Microservice Chassis
Spring Boot / Spring Cloud Suite
Shopping
Cart
Shipping
insurance
Anti
Fraud
Discount
Shipping
Cost
Estimation
Federated Micro-services
…
XX Id,
& Version,
XX Id,
YY Id
Z-specific data & behaviors,
for each Y of X
T-specific data & behaviors,
for each Y of X
U-specific data & behaviors,
for each Y of X
V-specific config (input)
for each Y of X
Easy to extend by addition of a
new federated service
Production-ready Microservices
Each service exposes health checks & metrics
/health
/metrics
/info
(built-in Spring Boot Actuator)
Each service produces semlogs used by monitoring
ELK + Worker
Each service is instrumented for distributed tracing
ZIPKIN (Sleuth)
Zipkin - your new debugger
Event-Driven
Architecture
WHY Event-Driven
Architecture?
DISTRIBUTE data across services for fast
Eventual Consistency
TEMPORAL Decoupling between services
(reduced failure area)
Events Senders and Receivers DON’T
KNOW each other (Decoupling)
Event-Driven Architecture in practice
One event bus with one shared topic
RabbitMQ
Everyone Broadcasts to Everyone
Exchange type: Fanout (or Headers)
Choreography over Orchestration
No central coordinator, control is
decentralized
Choreography over
orchestration
Init Pricing
V
UX
T
Update Amt Command
Amt
Updated
X
Updated
Pricing
Failed
T
Planed
V
ToReview
Event-Driven
Architecture
≠
Event Sourcing
Event Sourcing: a
persistence style
(events as private schema)
Event-Driven Architecture:
an integration style
(events as published contracts)
Can change whenever I want
Can never change once used
Contracts are forever!
Robustness rules
• MUST_IGNORE events & fields
you don’t know
• NEVER_REMOVE an existing
field or event
• ALWAYS_ADD new fields for
changes
protobuf, avro Consumer-Driven
Contracts
Which language in the events?
B
ACL
B
Events
A
Events
See: DDD /Context Mapping
Passenger safety
Propulsion
Car to ground link
Passenger safety
Propulsion
Car to ground link
DDD / Bounded
Contexts!
DDD beyond the infamous repository pattern - GeeCon Prague 2018

DDD beyond the infamous repository pattern - GeeCon Prague 2018