SlideShare a Scribd company logo
Building Rich
Domain Models
with DDD and TDD
ivan.paulovich@betssongroup.comhttps://paulovich.net
Ivan Paulovich
Betsson Dev'talk #3
Stockholm – September 12th, 2018
@ivanpaulovich
Ivan Paulovich
PhotobyRafaelaBiazionUnsplash
30+ Microsoft Certifications
paulovich.net
Developer
Betsson Wallet Team
• Seniors Developers
• Agile Team
• Business Oriented
• .NET – SQL Server – Angular
• Stockholm Office
• We are hiring!
How to shoot yourself in the foot:
1. Design your application starting from the data model.
2. Create your domain model by reverse engineering.
3. Pretend that you’re doing TDD and start testing your domain
classes.
• Particularly getters and setters.
4. Now start testing the logic with Integration Tests and get stuck by
test data and related issues.
5. Declare that TDD provides no benefit and only slows you down.
6. Comment tests in your Continuous Integration process.
7. Keep on whining.
Alberto Brandolini
04/59
Domain-Driven
Design
Tiny Domain Objects
Exploratory Programming
Focus on Unit Tests
Frequent Short Cycles
Quick Feedback
Self Explanatory Coding
Frequent Rewriting
Confidence to Change
Test-Driven
Development
05/59
A Customer Entity with Primitive Obsession...
06/59
Primitive Obsession Leads to Services Like..
• Needs to verify for required parameters,
Data Format and Data Range.
• Services are unnecessary Big and Fat.
• Easy to confuse one parameter with the
another.
07/59
• Not a technology.
• Not a methodology.
• Set of principles and patterns for focusing
the design effort where it matters most.
08/59
A Customer Entity Using Value Objects..
09/59
Business Rules Enforced Through Value Objects
• The simple existence of a Value Object means that it is valid.
• No need to verify parameters values on every method.
• Services are thinner and smaller when using Value Objets.
10/59
DDD express the Model with
Value Objects, Entities and Services.
Some Entities act as root of Aggregates.
11/59
An Example with Some Use Cases
• A customer can register a new account using its
personal details.
• Allow a customer to deposit funds into an existing
account.
• Allow to withdraw from an existing account.
• Do not allow to withdraw more than the current
balance.
12/59
Account Number 4444-6 (Day-to-Day)
Date Description Debit (SEK) Credit (SEK) Balance (SEK)
01-08-2018 Initial Balance 50,000
03-08-2018 Withdrawn 10,000 40,000
07-08-2018 Withdrawn 5,000 35,000
17-09-2018 Deposited 7,000 42,000
Account Number 7777-0 (Savings)
Date Description Debit (SEK) Credit (SEK) Balance (SEK)
01-09-2018 Initial Balance 10,000
Customer 5557-8
13/59
Some Noums and Verbs are Useful
• A customer can register a new account using its
personal details.
• Allow a customer to deposit funds into an
existing account.
• Allow to withdraw from an existing account.
• Do not allow to withdraw more than the current
balance.
14/59
Customer
Account
Credit
First Name
Last Name
Opening Date
Personnummer
Debit
Amount
Transaction
Date
Description
Tactical-Design
Mobile Phone
Number
Amount
Transaction
Date
Description
15/59
Customer
Account
Credit
First Name
Last Name
Opening Date
Personnummer
Debit
Amount
Transaction
Date
Description
Tactical-Design
Mobile Phone
Number
Amount
Transaction
Date
Description
16/59
Customer
Account
Credit
First Name
Last Name
Opening Date
Personnummer
Debit
Amount
Transaction
Date
Description
Tactical-Design
Mobile Phone
Number
Personal Expenses
Bounded Context
Amount
Transaction
Date
Description
17/59
Domain Model
Terms
Names of
Bounded Contexts
Terminology of Large-scale
Structures
DDD Patterns
Names
Business Terms
Developers Don’t
Understand
Business Terms
Everyone Uses
That Don’t Appear
in Design
Technical Aspects
of Design
Technical
Terms
Technical Design
Patterns
Developers Domain Experts
Ubiquitous
Language
18/59
Entities
• Have a unique identity.
• Are mutable or not.
• Refer others entities by their IDs.
19/59
Aggregate Roots (Are Entities)
• Refer other aggregates by identity only.
• Scope of consistency inside the aggregate boundaries.
• Eventual consistency between aggregates.
• Aggregates are small.
• Aggregates implement behaviors.
• Entity + Repository ~ Aggregate
• One Aggregate Root for every Entity is a Code Smell.
20/59
An Aggregate Root is not your Entire
Model
21/59
An Aggregate Root
22/59
Account Aggregate Root
03/59
Account Aggregate Root
It is an Entity
24/59
Account Aggregate Root
It is an Entity
Only mandatory fields are
required in the constructor
25/59
Account Aggregate Root
It is an Entity
Only mandatory fields are
required in the constructor
Implements behaviors which maintain
the state consistent.
26/59
Account Aggregate Root
It is an Entity
Factory method to restore state.
Only mandatory fields are
required in the constructor
Implements behaviors which maintain
the state consistent.
27/59
Value Objects
• Immutable.
• Have no explicit identity.
• Unique by the comparison of the attributes.
• Used to describe, measure or quantify an Entity.
First Name Last Name
Personnummer
Mobile Phone
Number
Amount Description
28/59
Personal Expenses
Bounded Context
.NET
Bounded Context
Mobile Phone
Number
string
29/59
Personal Expenses
Bounded Context
.NET
Bounded Context
Mobile Phone
Number
string
Clone
Compare
CompareOrdinal
CompareTo
Concat
Contains
Copy
CopyTo
Create
EndsWith
Equals
Format
GetEnumerator
GetHashCode
GetTypeCode
IndexOf
IndexOfAny
Insert
Intern
IsInterned
IsNormalized
IsNullOrEmpty
IsNullOrWhiteSpace
Join
LastIndexOf
LastIndexOfAny
Normalize
PadLeft
PadRight
Remove
Replace
Split
StartsWith
Substring
ToCharArray
ToLower
ToLowerInvariant
ToString
ToUpper
ToUpperInvariant
Trim
TrimEnd
TrimStart
30/59
Personal Expenses
Bounded Context
.NET
Bounded Context
Mobile Phone
Number
Create
GetAreaCode
GetLastFourDigits
ToString
string
Clone
Compare
CompareOrdinal
CompareTo
Concat
Contains
Copy
CopyTo
Create
EndsWith
Equals
Format
GetEnumerator
GetHashCode
GetTypeCode
IndexOf
IndexOfAny
Insert
Intern
IsInterned
IsNormalized
IsNullOrEmpty
IsNullOrWhiteSpace
Join
LastIndexOf
LastIndexOfAny
Normalize
PadLeft
PadRight
Remove
Replace
Split
StartsWith
Substring
ToCharArray
ToLower
ToLowerInvariant
ToString
ToUpper
ToUpperInvariant
Trim
TrimEnd
TrimStart
31/59
.NET
Bounded Context
Thread
Personal Expenses
Bounded Context
.NET
Bounded Context
Personal Expenses
Bounded Context
We only pay for the complexity
we really use
string
Phone Number
Thread
nullstring int
Reflection
double
collection
HttpClient
Without Value Objects With Value Objects
We bring the .NET Framework Complexity
into our Bounded Context.
nullint
Reflection
double
collection
HttpClient
32/59
Personnummer Value Object
33/59
First-Class Collections
• Each collection should be wrapped in its own class¹.
• Classes that contains collections do not contains any other
variable.
• Behaviors have a home.
• When necessary return immutable collection copies.
Account Transaction1:N
¹The ThoughtWorks Anthology: Essays on Software Technology and Innovation (Pragmatic Programmers), 2008
34/59
First-Class TransactionCollection
35/59
First-Class TransactionCollection
¹Growing Object-Oriented Software Guided by Tests, 2010
36/59
Copy collections and mutable objects
when passing them between objects.¹
How to Use the TransactionCollection Class
37/59
How to Use the TransactionCollection Class
The GetBalance() implementation belongs to
the TransactionCollection class.
38/59
How to Use the TransactionCollection Class
The GetBalance() implementation belongs to
the TransactionCollection class.
Composite simpler than
the sum of its parts
39/59
Write a failing
acceptance test
Write a
failing
unit test
Make the
test pass
Refactor
Inner and outer feedback loops in TDD
40/59
41/59
42/59
43/59
44/59
45/59
46/59
47/59
Opinionated DDD/TDD
• Sometimes I implement too much of the Domain Model. Then
return covering it with unit tests.
• By knowing the DDD patterns I underestimate the TDD value then
I'm slapped in the face.
• My goal is to maintain a high test coverage on the Domain
Model.
• If testing is hard. It is an architectural issue!
48/59
I won’t reverse engineer my
data model to create a
domain model.
49/59
The Stable Dependencies Principle¹
¹Clean Architecture, Robert C. Martin, 201750/59
The Stable Dependencies Principle
Infrastructure Web
Domain
Application
51/59
The Stable Dependencies Principle
Infrastructure Web
Domain
Application
Shining Framework Shining Library
52/59
The Stable Dependencies Principle
Infrastructure Web
Domain
Application
Shining Framework Shining Library
53/59
Entities
Use Cases
Controllers
External Interfaces
DB
Isolate the Domain with a Layered Architecture
54/59
Outside In
Controllers > Use Cases > Aggregates > Value Objects
Inside Out
1. Aggregates > Value Objects
2. Use Cases
3. Controllers
Testing Strategies
55/59
DDD Patterns
Ubiquitous Language
Testing
Application Design
Implementation Samples
Quick Review
56/59
DDD Patterns
Ubiquitous Language
Testing
Application Design
Implementation Samples
Quick Review
57/59
Implementation Samples
• Clean Architecture
• Hexagonal Architecture
• Event Sourcing
• DDD
• TDD
• Microservices
58/59
Resources
• Domain-driven Design, Eric J. Evans, 2003
• The ThoughtWorks Anthology: Essays on Software Technology
and Innovation (Pragmatic Programmers), 2008
• Clean Architecture, Robert C. Martin, 2017
• Growing Object-Oriented Software, Guided by Tests, 1st
Edition, 2009
• Secure by Design, Dan Bergh Johnsson, Daniel Deogun, Daniel
Sawano, 2018
• Domain-Driven Design Quickly, 2007
• Effective Aggregate Design, Vaughn Vernon, 2011
59/59

More Related Content

What's hot

Introduction to DDD
Introduction to DDDIntroduction to DDD
Introduction to DDD
Eduards Sizovs
 
Domain Driven Design Quickly
Domain Driven Design QuicklyDomain Driven Design Quickly
Domain Driven Design Quickly
Mariam Hakobyan
 
Domain Driven Design (Ultra) Distilled
Domain Driven Design (Ultra) DistilledDomain Driven Design (Ultra) Distilled
Domain Driven Design (Ultra) Distilled
Nicola Costantino
 
Domain Driven Design(DDD) Presentation
Domain Driven Design(DDD) PresentationDomain Driven Design(DDD) Presentation
Domain Driven Design(DDD) Presentation
Oğuzhan Soykan
 
Domain Driven Design Introduction
Domain Driven Design IntroductionDomain Driven Design Introduction
Domain Driven Design Introduction
wojtek_s
 
Domain driven design
Domain driven designDomain driven design
Domain driven design
Amit Mukherjee
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
Nader Albert
 
DDD Tactical Design with Clean Architecture - Ivan Paulovich
DDD Tactical Design with Clean Architecture - Ivan PaulovichDDD Tactical Design with Clean Architecture - Ivan Paulovich
DDD Tactical Design with Clean Architecture - Ivan Paulovich
Ivan Paulovich
 
Domain driven design and model driven development
Domain driven design and model driven developmentDomain driven design and model driven development
Domain driven design and model driven development
Dmitry Geyzersky
 
Strategic Domain-Driven Design by Nick Tune at #AgileIndia2019
Strategic Domain-Driven Design by Nick Tune at #AgileIndia2019Strategic Domain-Driven Design by Nick Tune at #AgileIndia2019
Strategic Domain-Driven Design by Nick Tune at #AgileIndia2019
Agile India
 
Clean architecture
Clean architectureClean architecture
Clean architecture
Lieven Doclo
 
Domain Driven Design - Strategic Patterns and Microservices
Domain Driven Design - Strategic Patterns and MicroservicesDomain Driven Design - Strategic Patterns and Microservices
Domain Driven Design - Strategic Patterns and Microservices
Radosław Maziarka
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
Hannah Farrugia
 
Domain Driven Design
Domain Driven Design Domain Driven Design
Domain Driven Design
Araf Karsh Hamid
 
A Practical Guide to Domain Driven Design: Presentation Slides
A Practical Guide to Domain Driven Design: Presentation SlidesA Practical Guide to Domain Driven Design: Presentation Slides
A Practical Guide to Domain Driven Design: Presentation Slides
thinkddd
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
Nikolay Vasilev
 
Domain-Driven Design
Domain-Driven DesignDomain-Driven Design
Domain-Driven Design
Andriy Buday
 
Clean architecture - Protecting the Domain
Clean architecture - Protecting the DomainClean architecture - Protecting the Domain
Clean architecture - Protecting the Domain
Victor Rentea
 
Baby steps to Domain-Driven Design
Baby steps to Domain-Driven DesignBaby steps to Domain-Driven Design
Baby steps to Domain-Driven Design
Žilvinas Kuusas
 

What's hot (20)

Introduction to DDD
Introduction to DDDIntroduction to DDD
Introduction to DDD
 
Domain Driven Design Quickly
Domain Driven Design QuicklyDomain Driven Design Quickly
Domain Driven Design Quickly
 
Domain Driven Design (Ultra) Distilled
Domain Driven Design (Ultra) DistilledDomain Driven Design (Ultra) Distilled
Domain Driven Design (Ultra) Distilled
 
Domain Driven Design(DDD) Presentation
Domain Driven Design(DDD) PresentationDomain Driven Design(DDD) Presentation
Domain Driven Design(DDD) Presentation
 
Domain Driven Design Introduction
Domain Driven Design IntroductionDomain Driven Design Introduction
Domain Driven Design Introduction
 
Domain driven design
Domain driven designDomain driven design
Domain driven design
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
 
DDD Tactical Design with Clean Architecture - Ivan Paulovich
DDD Tactical Design with Clean Architecture - Ivan PaulovichDDD Tactical Design with Clean Architecture - Ivan Paulovich
DDD Tactical Design with Clean Architecture - Ivan Paulovich
 
Domain driven design and model driven development
Domain driven design and model driven developmentDomain driven design and model driven development
Domain driven design and model driven development
 
Strategic Domain-Driven Design by Nick Tune at #AgileIndia2019
Strategic Domain-Driven Design by Nick Tune at #AgileIndia2019Strategic Domain-Driven Design by Nick Tune at #AgileIndia2019
Strategic Domain-Driven Design by Nick Tune at #AgileIndia2019
 
Clean architecture
Clean architectureClean architecture
Clean architecture
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
 
Domain Driven Design - Strategic Patterns and Microservices
Domain Driven Design - Strategic Patterns and MicroservicesDomain Driven Design - Strategic Patterns and Microservices
Domain Driven Design - Strategic Patterns and Microservices
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
 
Domain Driven Design
Domain Driven Design Domain Driven Design
Domain Driven Design
 
A Practical Guide to Domain Driven Design: Presentation Slides
A Practical Guide to Domain Driven Design: Presentation SlidesA Practical Guide to Domain Driven Design: Presentation Slides
A Practical Guide to Domain Driven Design: Presentation Slides
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
 
Domain-Driven Design
Domain-Driven DesignDomain-Driven Design
Domain-Driven Design
 
Clean architecture - Protecting the Domain
Clean architecture - Protecting the DomainClean architecture - Protecting the Domain
Clean architecture - Protecting the Domain
 
Baby steps to Domain-Driven Design
Baby steps to Domain-Driven DesignBaby steps to Domain-Driven Design
Baby steps to Domain-Driven Design
 

Similar to Building rich domain models with ddd and tdd ivan paulovich - betsson

Exploratory Testing As Code Eurostar23
Exploratory Testing As Code Eurostar23Exploratory Testing As Code Eurostar23
Exploratory Testing As Code Eurostar23
Brendan Connolly
 
Exploratory Testing As Code
Exploratory Testing As CodeExploratory Testing As Code
Exploratory Testing As Code
Brendan Connolly
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
Steven Smith
 
Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016
Steven Smith
 
How Custom is your Org? CEER at Dreamforce 2019
How Custom is your Org?  CEER at Dreamforce 2019How Custom is your Org?  CEER at Dreamforce 2019
How Custom is your Org? CEER at Dreamforce 2019
Steven Herod
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
Steven Smith
 
Define and Manage Requirements with IBM Rational Requirements Composer
Define and Manage Requirements with IBM Rational Requirements ComposerDefine and Manage Requirements with IBM Rational Requirements Composer
Define and Manage Requirements with IBM Rational Requirements ComposerAlan Kan
 
Trends in software testing by Eka TechServ
Trends in software testing  by Eka TechServTrends in software testing  by Eka TechServ
Trends in software testing by Eka TechServ
ekatechserv
 
Application Architecture
Application ArchitectureApplication Architecture
Application Architecture
Lars-Erik Kindblad
 
Approaching ATDD/BDD
Approaching ATDD/BDDApproaching ATDD/BDD
Approaching ATDD/BDD
Dhaval Dalal
 
Pragmatic Architecture in .NET
Pragmatic Architecture in .NETPragmatic Architecture in .NET
Pragmatic Architecture in .NET
housecor
 
Software reengineering for Developers
Software reengineering for DevelopersSoftware reengineering for Developers
Software reengineering for Developers
Bradley Irby
 
Df12 Performance Tuning
Df12 Performance TuningDf12 Performance Tuning
Df12 Performance Tuning
Stuart Bernstein
 
Neoito — Design patterns and depenedency injection
Neoito — Design patterns and depenedency injectionNeoito — Design patterns and depenedency injection
Neoito — Design patterns and depenedency injection
Neoito
 
Software Design principales
Software Design principalesSoftware Design principales
Software Design principales
ABDEL RAHMAN KARIM
 
Apex Enterprise Patterns Galore - Boston, MA dev group meeting 062719
Apex Enterprise Patterns Galore - Boston, MA dev group meeting 062719Apex Enterprise Patterns Galore - Boston, MA dev group meeting 062719
Apex Enterprise Patterns Galore - Boston, MA dev group meeting 062719
BingWang77
 
Improving The Quality of Existing Software
Improving The Quality of Existing SoftwareImproving The Quality of Existing Software
Improving The Quality of Existing Software
Steven Smith
 
Agile, User Stories, Domain Driven Design
Agile, User Stories, Domain Driven DesignAgile, User Stories, Domain Driven Design
Agile, User Stories, Domain Driven Design
Araf Karsh Hamid
 
Managing an Experimentation Platform by LinkedIn Product Leader
Managing an Experimentation Platform by LinkedIn Product LeaderManaging an Experimentation Platform by LinkedIn Product Leader
Managing an Experimentation Platform by LinkedIn Product Leader
Product School
 

Similar to Building rich domain models with ddd and tdd ivan paulovich - betsson (20)

Exploratory Testing As Code Eurostar23
Exploratory Testing As Code Eurostar23Exploratory Testing As Code Eurostar23
Exploratory Testing As Code Eurostar23
 
Exploratory Testing As Code
Exploratory Testing As CodeExploratory Testing As Code
Exploratory Testing As Code
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 
Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016
 
How Custom is your Org? CEER at Dreamforce 2019
How Custom is your Org?  CEER at Dreamforce 2019How Custom is your Org?  CEER at Dreamforce 2019
How Custom is your Org? CEER at Dreamforce 2019
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 
Define and Manage Requirements with IBM Rational Requirements Composer
Define and Manage Requirements with IBM Rational Requirements ComposerDefine and Manage Requirements with IBM Rational Requirements Composer
Define and Manage Requirements with IBM Rational Requirements Composer
 
Trends in software testing by Eka TechServ
Trends in software testing  by Eka TechServTrends in software testing  by Eka TechServ
Trends in software testing by Eka TechServ
 
Application Architecture
Application ArchitectureApplication Architecture
Application Architecture
 
Approaching ATDD/BDD
Approaching ATDD/BDDApproaching ATDD/BDD
Approaching ATDD/BDD
 
Pragmatic Architecture in .NET
Pragmatic Architecture in .NETPragmatic Architecture in .NET
Pragmatic Architecture in .NET
 
Software reengineering for Developers
Software reengineering for DevelopersSoftware reengineering for Developers
Software reengineering for Developers
 
Df12 Performance Tuning
Df12 Performance TuningDf12 Performance Tuning
Df12 Performance Tuning
 
Neoito — Design patterns and depenedency injection
Neoito — Design patterns and depenedency injectionNeoito — Design patterns and depenedency injection
Neoito — Design patterns and depenedency injection
 
Software Design principales
Software Design principalesSoftware Design principales
Software Design principales
 
Restructuring rails
Restructuring railsRestructuring rails
Restructuring rails
 
Apex Enterprise Patterns Galore - Boston, MA dev group meeting 062719
Apex Enterprise Patterns Galore - Boston, MA dev group meeting 062719Apex Enterprise Patterns Galore - Boston, MA dev group meeting 062719
Apex Enterprise Patterns Galore - Boston, MA dev group meeting 062719
 
Improving The Quality of Existing Software
Improving The Quality of Existing SoftwareImproving The Quality of Existing Software
Improving The Quality of Existing Software
 
Agile, User Stories, Domain Driven Design
Agile, User Stories, Domain Driven DesignAgile, User Stories, Domain Driven Design
Agile, User Stories, Domain Driven Design
 
Managing an Experimentation Platform by LinkedIn Product Leader
Managing an Experimentation Platform by LinkedIn Product LeaderManaging an Experimentation Platform by LinkedIn Product Leader
Managing an Experimentation Platform by LinkedIn Product Leader
 

More from Ivan Paulovich

Clean Architecture Essentials - Stockholm Software Craftsmanship
Clean Architecture Essentials - Stockholm Software CraftsmanshipClean Architecture Essentials - Stockholm Software Craftsmanship
Clean Architecture Essentials - Stockholm Software Craftsmanship
Ivan Paulovich
 
Clean Architecture Essentials @ivanpaulovich
Clean Architecture Essentials @ivanpaulovichClean Architecture Essentials @ivanpaulovich
Clean Architecture Essentials @ivanpaulovich
Ivan Paulovich
 
Moving to Microservices
Moving to MicroservicesMoving to Microservices
Moving to Microservices
Ivan Paulovich
 
Produzindo e consumindo um stream de eventos
Produzindo e consumindo um stream de eventosProduzindo e consumindo um stream de eventos
Produzindo e consumindo um stream de eventos
Ivan Paulovich
 
Como uma aplicação baseada em fluxo de dados pode ampliar a segurança em crec...
Como uma aplicação baseada em fluxo de dados pode ampliar a segurança em crec...Como uma aplicação baseada em fluxo de dados pode ampliar a segurança em crec...
Como uma aplicação baseada em fluxo de dados pode ampliar a segurança em crec...
Ivan Paulovich
 
Como uma aplicação baseada em fluxo de dados pode ampliar a segurança em creches
Como uma aplicação baseada em fluxo de dados pode ampliar a segurança em crechesComo uma aplicação baseada em fluxo de dados pode ampliar a segurança em creches
Como uma aplicação baseada em fluxo de dados pode ampliar a segurança em creches
Ivan Paulovich
 
Aggregates com Event Sourcing
Aggregates com Event SourcingAggregates com Event Sourcing
Aggregates com Event Sourcing
Ivan Paulovich
 
Estudo do eShopOnContainers
Estudo do eShopOnContainersEstudo do eShopOnContainers
Estudo do eShopOnContainers
Ivan Paulovich
 
Introdução ao Domain-Driven-Design (DDD)
Introdução ao Domain-Driven-Design (DDD)Introdução ao Domain-Driven-Design (DDD)
Introdução ao Domain-Driven-Design (DDD)
Ivan Paulovich
 
Princípios SOLID de OO usando .NET
Princípios SOLID de OO usando .NETPrincípios SOLID de OO usando .NET
Princípios SOLID de OO usando .NET
Ivan Paulovich
 
Utilize o vso e publique imagens docker Global Azure Bootcamp - BH
Utilize o vso e publique imagens docker Global Azure Bootcamp - BHUtilize o vso e publique imagens docker Global Azure Bootcamp - BH
Utilize o vso e publique imagens docker Global Azure Bootcamp - BH
Ivan Paulovich
 
Windows Azure Mobile Services InfoTech 2014
Windows Azure Mobile Services InfoTech 2014Windows Azure Mobile Services InfoTech 2014
Windows Azure Mobile Services InfoTech 2014
Ivan Paulovich
 
Mercado de ti e suas oportunidades
Mercado de ti e suas oportunidadesMercado de ti e suas oportunidades
Mercado de ti e suas oportunidadesIvan Paulovich
 
Construindo Apps Com SignalR
Construindo Apps Com SignalRConstruindo Apps Com SignalR
Construindo Apps Com SignalR
Ivan Paulovich
 
Construindo apps de tempo real com SignalR
Construindo apps de tempo real com SignalRConstruindo apps de tempo real com SignalR
Construindo apps de tempo real com SignalR
Ivan Paulovich
 
Construindo Apps com ASP.NET SignalR
Construindo Apps com ASP.NET SignalRConstruindo Apps com ASP.NET SignalR
Construindo Apps com ASP.NET SignalRIvan Paulovich
 
Levando sua aplicação para a nuvem
Levando sua aplicação para a nuvemLevando sua aplicação para a nuvem
Levando sua aplicação para a nuvemIvan Paulovich
 
Conhecendo os recursos do ASP.NET Web API
Conhecendo os recursos do ASP.NET Web APIConhecendo os recursos do ASP.NET Web API
Conhecendo os recursos do ASP.NET Web APIIvan Paulovich
 
Criando aplicativos para Windows 8 usando apenas HTML5 e Javascript
Criando aplicativos para Windows 8 usando apenas HTML5 e JavascriptCriando aplicativos para Windows 8 usando apenas HTML5 e Javascript
Criando aplicativos para Windows 8 usando apenas HTML5 e JavascriptIvan Paulovich
 

More from Ivan Paulovich (19)

Clean Architecture Essentials - Stockholm Software Craftsmanship
Clean Architecture Essentials - Stockholm Software CraftsmanshipClean Architecture Essentials - Stockholm Software Craftsmanship
Clean Architecture Essentials - Stockholm Software Craftsmanship
 
Clean Architecture Essentials @ivanpaulovich
Clean Architecture Essentials @ivanpaulovichClean Architecture Essentials @ivanpaulovich
Clean Architecture Essentials @ivanpaulovich
 
Moving to Microservices
Moving to MicroservicesMoving to Microservices
Moving to Microservices
 
Produzindo e consumindo um stream de eventos
Produzindo e consumindo um stream de eventosProduzindo e consumindo um stream de eventos
Produzindo e consumindo um stream de eventos
 
Como uma aplicação baseada em fluxo de dados pode ampliar a segurança em crec...
Como uma aplicação baseada em fluxo de dados pode ampliar a segurança em crec...Como uma aplicação baseada em fluxo de dados pode ampliar a segurança em crec...
Como uma aplicação baseada em fluxo de dados pode ampliar a segurança em crec...
 
Como uma aplicação baseada em fluxo de dados pode ampliar a segurança em creches
Como uma aplicação baseada em fluxo de dados pode ampliar a segurança em crechesComo uma aplicação baseada em fluxo de dados pode ampliar a segurança em creches
Como uma aplicação baseada em fluxo de dados pode ampliar a segurança em creches
 
Aggregates com Event Sourcing
Aggregates com Event SourcingAggregates com Event Sourcing
Aggregates com Event Sourcing
 
Estudo do eShopOnContainers
Estudo do eShopOnContainersEstudo do eShopOnContainers
Estudo do eShopOnContainers
 
Introdução ao Domain-Driven-Design (DDD)
Introdução ao Domain-Driven-Design (DDD)Introdução ao Domain-Driven-Design (DDD)
Introdução ao Domain-Driven-Design (DDD)
 
Princípios SOLID de OO usando .NET
Princípios SOLID de OO usando .NETPrincípios SOLID de OO usando .NET
Princípios SOLID de OO usando .NET
 
Utilize o vso e publique imagens docker Global Azure Bootcamp - BH
Utilize o vso e publique imagens docker Global Azure Bootcamp - BHUtilize o vso e publique imagens docker Global Azure Bootcamp - BH
Utilize o vso e publique imagens docker Global Azure Bootcamp - BH
 
Windows Azure Mobile Services InfoTech 2014
Windows Azure Mobile Services InfoTech 2014Windows Azure Mobile Services InfoTech 2014
Windows Azure Mobile Services InfoTech 2014
 
Mercado de ti e suas oportunidades
Mercado de ti e suas oportunidadesMercado de ti e suas oportunidades
Mercado de ti e suas oportunidades
 
Construindo Apps Com SignalR
Construindo Apps Com SignalRConstruindo Apps Com SignalR
Construindo Apps Com SignalR
 
Construindo apps de tempo real com SignalR
Construindo apps de tempo real com SignalRConstruindo apps de tempo real com SignalR
Construindo apps de tempo real com SignalR
 
Construindo Apps com ASP.NET SignalR
Construindo Apps com ASP.NET SignalRConstruindo Apps com ASP.NET SignalR
Construindo Apps com ASP.NET SignalR
 
Levando sua aplicação para a nuvem
Levando sua aplicação para a nuvemLevando sua aplicação para a nuvem
Levando sua aplicação para a nuvem
 
Conhecendo os recursos do ASP.NET Web API
Conhecendo os recursos do ASP.NET Web APIConhecendo os recursos do ASP.NET Web API
Conhecendo os recursos do ASP.NET Web API
 
Criando aplicativos para Windows 8 usando apenas HTML5 e Javascript
Criando aplicativos para Windows 8 usando apenas HTML5 e JavascriptCriando aplicativos para Windows 8 usando apenas HTML5 e Javascript
Criando aplicativos para Windows 8 usando apenas HTML5 e Javascript
 

Recently uploaded

openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
Shane Coughlan
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Crescat
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
Łukasz Chruściel
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
timtebeek1
 
What is Augmented Reality Image Tracking
What is Augmented Reality Image TrackingWhat is Augmented Reality Image Tracking
What is Augmented Reality Image Tracking
pavan998932
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
TheSMSPoint
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Mind IT Systems
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Neo4j
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
Deuglo Infosystem Pvt Ltd
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
Aftab Hussain
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Łukasz Chruściel
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
Ayan Halder
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
Google
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
Roshan Dwivedi
 

Recently uploaded (20)

openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
 
What is Augmented Reality Image Tracking
What is Augmented Reality Image TrackingWhat is Augmented Reality Image Tracking
What is Augmented Reality Image Tracking
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
 

Building rich domain models with ddd and tdd ivan paulovich - betsson

  • 1. Building Rich Domain Models with DDD and TDD ivan.paulovich@betssongroup.comhttps://paulovich.net Ivan Paulovich Betsson Dev'talk #3 Stockholm – September 12th, 2018 @ivanpaulovich
  • 2. Ivan Paulovich PhotobyRafaelaBiazionUnsplash 30+ Microsoft Certifications paulovich.net Developer
  • 3. Betsson Wallet Team • Seniors Developers • Agile Team • Business Oriented • .NET – SQL Server – Angular • Stockholm Office • We are hiring!
  • 4. How to shoot yourself in the foot: 1. Design your application starting from the data model. 2. Create your domain model by reverse engineering. 3. Pretend that you’re doing TDD and start testing your domain classes. • Particularly getters and setters. 4. Now start testing the logic with Integration Tests and get stuck by test data and related issues. 5. Declare that TDD provides no benefit and only slows you down. 6. Comment tests in your Continuous Integration process. 7. Keep on whining. Alberto Brandolini 04/59
  • 5. Domain-Driven Design Tiny Domain Objects Exploratory Programming Focus on Unit Tests Frequent Short Cycles Quick Feedback Self Explanatory Coding Frequent Rewriting Confidence to Change Test-Driven Development 05/59
  • 6. A Customer Entity with Primitive Obsession... 06/59
  • 7. Primitive Obsession Leads to Services Like.. • Needs to verify for required parameters, Data Format and Data Range. • Services are unnecessary Big and Fat. • Easy to confuse one parameter with the another. 07/59
  • 8. • Not a technology. • Not a methodology. • Set of principles and patterns for focusing the design effort where it matters most. 08/59
  • 9. A Customer Entity Using Value Objects.. 09/59
  • 10. Business Rules Enforced Through Value Objects • The simple existence of a Value Object means that it is valid. • No need to verify parameters values on every method. • Services are thinner and smaller when using Value Objets. 10/59
  • 11. DDD express the Model with Value Objects, Entities and Services. Some Entities act as root of Aggregates. 11/59
  • 12. An Example with Some Use Cases • A customer can register a new account using its personal details. • Allow a customer to deposit funds into an existing account. • Allow to withdraw from an existing account. • Do not allow to withdraw more than the current balance. 12/59
  • 13. Account Number 4444-6 (Day-to-Day) Date Description Debit (SEK) Credit (SEK) Balance (SEK) 01-08-2018 Initial Balance 50,000 03-08-2018 Withdrawn 10,000 40,000 07-08-2018 Withdrawn 5,000 35,000 17-09-2018 Deposited 7,000 42,000 Account Number 7777-0 (Savings) Date Description Debit (SEK) Credit (SEK) Balance (SEK) 01-09-2018 Initial Balance 10,000 Customer 5557-8 13/59
  • 14. Some Noums and Verbs are Useful • A customer can register a new account using its personal details. • Allow a customer to deposit funds into an existing account. • Allow to withdraw from an existing account. • Do not allow to withdraw more than the current balance. 14/59
  • 15. Customer Account Credit First Name Last Name Opening Date Personnummer Debit Amount Transaction Date Description Tactical-Design Mobile Phone Number Amount Transaction Date Description 15/59
  • 16. Customer Account Credit First Name Last Name Opening Date Personnummer Debit Amount Transaction Date Description Tactical-Design Mobile Phone Number Amount Transaction Date Description 16/59
  • 17. Customer Account Credit First Name Last Name Opening Date Personnummer Debit Amount Transaction Date Description Tactical-Design Mobile Phone Number Personal Expenses Bounded Context Amount Transaction Date Description 17/59
  • 18. Domain Model Terms Names of Bounded Contexts Terminology of Large-scale Structures DDD Patterns Names Business Terms Developers Don’t Understand Business Terms Everyone Uses That Don’t Appear in Design Technical Aspects of Design Technical Terms Technical Design Patterns Developers Domain Experts Ubiquitous Language 18/59
  • 19. Entities • Have a unique identity. • Are mutable or not. • Refer others entities by their IDs. 19/59
  • 20. Aggregate Roots (Are Entities) • Refer other aggregates by identity only. • Scope of consistency inside the aggregate boundaries. • Eventual consistency between aggregates. • Aggregates are small. • Aggregates implement behaviors. • Entity + Repository ~ Aggregate • One Aggregate Root for every Entity is a Code Smell. 20/59
  • 21. An Aggregate Root is not your Entire Model 21/59
  • 24. Account Aggregate Root It is an Entity 24/59
  • 25. Account Aggregate Root It is an Entity Only mandatory fields are required in the constructor 25/59
  • 26. Account Aggregate Root It is an Entity Only mandatory fields are required in the constructor Implements behaviors which maintain the state consistent. 26/59
  • 27. Account Aggregate Root It is an Entity Factory method to restore state. Only mandatory fields are required in the constructor Implements behaviors which maintain the state consistent. 27/59
  • 28. Value Objects • Immutable. • Have no explicit identity. • Unique by the comparison of the attributes. • Used to describe, measure or quantify an Entity. First Name Last Name Personnummer Mobile Phone Number Amount Description 28/59
  • 29. Personal Expenses Bounded Context .NET Bounded Context Mobile Phone Number string 29/59
  • 30. Personal Expenses Bounded Context .NET Bounded Context Mobile Phone Number string Clone Compare CompareOrdinal CompareTo Concat Contains Copy CopyTo Create EndsWith Equals Format GetEnumerator GetHashCode GetTypeCode IndexOf IndexOfAny Insert Intern IsInterned IsNormalized IsNullOrEmpty IsNullOrWhiteSpace Join LastIndexOf LastIndexOfAny Normalize PadLeft PadRight Remove Replace Split StartsWith Substring ToCharArray ToLower ToLowerInvariant ToString ToUpper ToUpperInvariant Trim TrimEnd TrimStart 30/59
  • 31. Personal Expenses Bounded Context .NET Bounded Context Mobile Phone Number Create GetAreaCode GetLastFourDigits ToString string Clone Compare CompareOrdinal CompareTo Concat Contains Copy CopyTo Create EndsWith Equals Format GetEnumerator GetHashCode GetTypeCode IndexOf IndexOfAny Insert Intern IsInterned IsNormalized IsNullOrEmpty IsNullOrWhiteSpace Join LastIndexOf LastIndexOfAny Normalize PadLeft PadRight Remove Replace Split StartsWith Substring ToCharArray ToLower ToLowerInvariant ToString ToUpper ToUpperInvariant Trim TrimEnd TrimStart 31/59
  • 32. .NET Bounded Context Thread Personal Expenses Bounded Context .NET Bounded Context Personal Expenses Bounded Context We only pay for the complexity we really use string Phone Number Thread nullstring int Reflection double collection HttpClient Without Value Objects With Value Objects We bring the .NET Framework Complexity into our Bounded Context. nullint Reflection double collection HttpClient 32/59
  • 34. First-Class Collections • Each collection should be wrapped in its own class¹. • Classes that contains collections do not contains any other variable. • Behaviors have a home. • When necessary return immutable collection copies. Account Transaction1:N ¹The ThoughtWorks Anthology: Essays on Software Technology and Innovation (Pragmatic Programmers), 2008 34/59
  • 36. First-Class TransactionCollection ¹Growing Object-Oriented Software Guided by Tests, 2010 36/59 Copy collections and mutable objects when passing them between objects.¹
  • 37. How to Use the TransactionCollection Class 37/59
  • 38. How to Use the TransactionCollection Class The GetBalance() implementation belongs to the TransactionCollection class. 38/59
  • 39. How to Use the TransactionCollection Class The GetBalance() implementation belongs to the TransactionCollection class. Composite simpler than the sum of its parts 39/59
  • 40. Write a failing acceptance test Write a failing unit test Make the test pass Refactor Inner and outer feedback loops in TDD 40/59
  • 41. 41/59
  • 42. 42/59
  • 43. 43/59
  • 44. 44/59
  • 45. 45/59
  • 46. 46/59
  • 47. 47/59
  • 48. Opinionated DDD/TDD • Sometimes I implement too much of the Domain Model. Then return covering it with unit tests. • By knowing the DDD patterns I underestimate the TDD value then I'm slapped in the face. • My goal is to maintain a high test coverage on the Domain Model. • If testing is hard. It is an architectural issue! 48/59
  • 49. I won’t reverse engineer my data model to create a domain model. 49/59
  • 50. The Stable Dependencies Principle¹ ¹Clean Architecture, Robert C. Martin, 201750/59
  • 51. The Stable Dependencies Principle Infrastructure Web Domain Application 51/59
  • 52. The Stable Dependencies Principle Infrastructure Web Domain Application Shining Framework Shining Library 52/59
  • 53. The Stable Dependencies Principle Infrastructure Web Domain Application Shining Framework Shining Library 53/59
  • 54. Entities Use Cases Controllers External Interfaces DB Isolate the Domain with a Layered Architecture 54/59
  • 55. Outside In Controllers > Use Cases > Aggregates > Value Objects Inside Out 1. Aggregates > Value Objects 2. Use Cases 3. Controllers Testing Strategies 55/59
  • 56. DDD Patterns Ubiquitous Language Testing Application Design Implementation Samples Quick Review 56/59
  • 57. DDD Patterns Ubiquitous Language Testing Application Design Implementation Samples Quick Review 57/59
  • 58. Implementation Samples • Clean Architecture • Hexagonal Architecture • Event Sourcing • DDD • TDD • Microservices 58/59
  • 59. Resources • Domain-driven Design, Eric J. Evans, 2003 • The ThoughtWorks Anthology: Essays on Software Technology and Innovation (Pragmatic Programmers), 2008 • Clean Architecture, Robert C. Martin, 2017 • Growing Object-Oriented Software, Guided by Tests, 1st Edition, 2009 • Secure by Design, Dan Bergh Johnsson, Daniel Deogun, Daniel Sawano, 2018 • Domain-Driven Design Quickly, 2007 • Effective Aggregate Design, Vaughn Vernon, 2011 59/59

Editor's Notes

  1. Thank you for joining the Betsson Meetup. I am going to talk about Domain-Driven Design and Test-Driven Development.
  2. First let me introduce myself, I am Ivan Paulovich and I moved to Stockholm earlier this year to be a Developer for Betsson. I used to be an MVP in asp.net for a few years and now I am in the MVP Reconnect Program. My background is Development, Architecture and Cloud and I earned few Microsoft Certifications in these areas. I support the Paulovich.net blog and I am active in GitHub.
  3. I work with those guys, we are team of seniors developers following agile practices and we deliver the features the business wants. Our tech stack is .NET, SQL Server and Angular. If you are open to discuss opportunities we are hiring! Try to talk with HR and those developers.
  4. Let’s begin with a sad and common story that I copied from Alberto Brandolini. Its about designing the software from the data model using reverse engineering to make the Domain Model fit within the Data Model. And by pretending doing TDD testing getters and setters. Doing integration tests and get stuck by test data and related issues. Disappointing about TDD benefits and removing tests from the CI.
  5. Fortunately we move to a more happier story where Domain-Driven Design and Test-Driven Development work together. Alone this topics are huge and I will explain how they can be used together. On one side DDD provides this Tiny Domain Objects, Exploratory Programming.. On the other side TDD with Unit Tests, short cycles and confidence to change. Both target a Self Explanatory Coding, Quick feedback and Rewriting. My strategy is to talk is to introduce DDD and bit by bit talk about TDD.
  6. Let’s explicit the problem: This is a Customer Entity, all the properties are strings. It does not have methods and all data are exposed as public.
  7. The previous class leads to Services like this, if wanna register a Customer the service receive string parameters that we need to verify for data range, format and what is mandatory or not. Usually it became unecessary big and fat also it is easy to confuse one parameter with another.
  8. Then we are enlightened with DDD. Which is not a technology, not a methodology. It is a set os principles and patterns for focus the design effort where it matters.
  9. I could replace the string properties with specialized classes that we call Value Objects, this tiny classes enforces the smallest business rules.
  10. And it leads to thinner Services, that do not require to validate the arguments of every method. The simple existence of a Value Object means that it is valid. A quick tip about services is that they do not have state.
  11. DDD express the Model with Value Objects, Entities and Services.. Some Entities are Aggregate Roots. At this moment it is not clear.
  12. So.. I will explain using Use Cases. A Customer can register a new account then deposit and withdraw funds. The customer can not withdraw more that the current balance.
  13. This table make the use cases clear. A customer can have multiple accounts, each account has a transaction history and we can get the balance any time.
  14. The previous use cases are useful to identify some noums and verbs. It helps do draw the initial Design.
  15. This figure is another representation the Domain. In blue the Entities and in green the Value Objects that describe the entities.
  16. The Customer and Account perform the Aggregate Root role, I am going to explain soon.
  17. And of course, this structures are only valid inside the Personal Expenses Bounded Context.
  18. The fundamentals of DDD is to build an Ubiquitous Language, this is the vocabulary that is shared between Developers and Domain Experts. Developers have jargons, they know technical stuff. And Domain Experts focus in the Business. There are some terms that both should know to create a shared language. The Domain Model Terms, Bounded Contexts, DDD pattterns names and high level structures. Everything else are not ubiquitous.
  19. The entity pattern requires that every entity has an unique id. The entity could be mutable or not, and they refer other entities by ID. In our example the Customer, Account, Credit and Debit are Entities.
  20. An Aggregate Root is a specialized Entity that control the scope of consistency inside the aggregate boundaries. Usually the aggregate root is a bunch of entities that are seen as one single unit. The aggregates are small, they implement behaviors with methods. And I advance that one entity plus one repository pattern are close to an Aggregate.
  21. Another way to explain the Aggregate Pattern, is by what it is not. The aggregate is not your Entire Model, the same way as this bunch of grapes that we can not identify the boundaries.
  22. Aggregate Roots are small as this bunch of grapes that we can see the boundaries. This way it is possible to maitain the consistency of the business rules.
  23. it simple do not exist if invalid
  24. it simple do not exist if invalid
  25. it simple do not exist if invalid
  26. it simple do not exist if invalid
  27. it simple do not exist if invalid
  28. it simple do not exist if invalid
  29. it simple do not exist if invalid
  30. it simple do not exist if invalid
  31. it simple do not exist if invalid
  32. it simple do not exist if invalid
  33. it simple do not exist if invalid
  34. it simple do not exist if invalid
  35. it simple do not exist if invalid
  36. If you're calling two setters in a row, you're missing a concept. Don't get trapped by datastore thinking. DDD and TDD are tools, seniors developers need to know.