DDD provides a set of patterns and practices for tackling complex business problems with software models. Learn the basics of DDD in this session, including several principles and patterns you can start using immediately even if your project hasn't otherwise embraced DDD. Examples will primarily use C#/.NET.
Big Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/ML
Introducing Domain Driven Design - codemash
1. No Content Here
(Reserved for Watermark)
Introducing Domain-
Driven Design (DDD)
@ardalis
Ardalis.com
Steve Smith
2. No Content Here
(Reserved for Watermark)
Tweet Away!
• Live Tweeting and Photos are encouraged
• Questions and Feedback are welcome
• Use #Codemash and/or #DDDesign
• (and mention @ardalis)
3. No Content Here
(Reserved for Watermark)
Online Training
See me after for:
• 1-month free Pluralsight pass
• 20% off any DevIQ course
4. No Content Here
(Reserved for Watermark)
https://ardalis.com/architecture-ebook
http://microsoft.com/net/learn/architecture
Sample:
https://github.com/dotnet-architecture/eShopOnWeb
Covers ASP.NET Core 2.x monolithic app development
along with several DDD principles and patterns.
Free Microsoft eBook
6. No Content Here
(Reserved for Watermark)
What is Domain-Driven Design?
Focus on the problem domain
Not the database, or even the code implementation
Tools for better communication and knowledge discovery
Patterns for modeling solutions
Without tight coupling to infrastructure concerns
8. No Content Here
(Reserved for Watermark)
Why You Should Care about DDD
History of
success with
complex
projects
Principles
& patterns to
solve difficult
problems
Clear, testable
code that
represents the
domain
Aligns with
practices from
experts’
experience
9. No Content Here
(Reserved for Watermark)
Flexible
Customer’s vision/perspective of the problem
Path through a very complex problem
Well-organized and easily tested code
Business logic lives in one place.
Many great patterns to leverage
Benefits of Domain Driven Design
10. No Content Here
(Reserved for Watermark)
While Domain-Driven Design provides many technical
benefits, such as maintainability, it should be applied
only to complex domains where the model and the
linguistic processes provide clear benefits in the
communication of complex information, and in the
formulation of a common understanding of the domain.
—Eric Evans
Domain-Driven Design
11. No Content Here
(Reserved for Watermark)
Time and Effort
Learning curve (why you’re here)
Only makes sense when there is complexity in the
problem
Team or Company Buy-In to DDD
Drawbacks of DDD
15. No Content Here
(Reserved for Watermark)
Core Domain
Your company (or product/division)’s primary space in which they solve customers’ problems
Key differentiator
Problem Domain
The overall domain of the specific problem your application will address / solve
Generic Subdomains
Separate applications or features your application must interact with. Not necessarily core to your app.
What are “domains”
16. No Content Here
(Reserved for Watermark)
Domains refer to problem spaces.
Domain Models and Bounded Contexts are
parts of a solution.
19. No Content Here
(Reserved for Watermark)
Explicitly define the context within which a
model applies… Keep the model strictly
consistent within these bounds, but don’t be
distracted or confused by issues outside.
—Eric Evans
24. No Content Here
(Reserved for Watermark)
Relates to the Solution you are building
The domain represents the problem your solution is solving
Core Domain – the business’s primary focus/industry
Sub-Domain – a particular area within a larger domain. Maps to a software
solution and bounded context.
Bounded Context
25. No Content Here
(Reserved for Watermark)
Context Maps
Client
Patient
Appointment
Notification
Exam Room
Client
Procedure Invoice
Notification
One DB
To Rule Them All
Appointment Scheduler Billing
vet-managr
The Dev Team
26. No Content Here
(Reserved for Watermark)
Context Maps
Client
Patient
Appointment
Notification
Exam Room
Client
Procedure Invoice
Notification
Appointment Scheduler Billing
DB DBAuthentication
User
Shared Kernel
vet-appt-sched
Team Awesome
vet-billing
Team Ultimate
27. No Content Here
(Reserved for Watermark)
Ubiquitous
Language
http://upload.wikimedia.org/wikipedia/commons/2/23/Rosetta_Stone.JPG
28. No Content Here
(Reserved for Watermark)
A project faces serious problems when
its language is fractured.
—Eric Evans
29. No Content Here
(Reserved for Watermark)
Ubiquitous Language
For a single Bounded Context
Used throughout that context, from
conversations to code
Bounded Contexts should also have
names, to aid in disambiguation.
30. No Content Here
(Reserved for Watermark)
Problem Domain
The specific problem the software you’re working on
is trying to solve.
Glossary of Terms
Core Domain
The key differentiator for the customer’s business – something
they must do well and cannot outsource.
Sub-Domains
Separate applications or features your software must
support or interact with.
Bounded Context
A specific responsibility, with explicit boundaries that
separate it from other parts of the system. Usually
corresponds to a specific Sub-Domain.
31. No Content Here
(Reserved for Watermark)
Context Mapping
The process of identifying bounded contexts and
their relationships to one another.
Glossary of Terms
Shared Kernel
Part of the model that is shared by two or more teams, who agree
not to change it without collaboration
Ubiquitous Language
A language using terms from the domain model that
programmers and domain experts use to discuss the system
within a particular bounded context.
35. No Content Here
(Reserved for Watermark)
BehaviorsSchedule an appointment for a checkup
Note a pet’s weight
Request lab work
Notify pet owner of vaccinations due
Accept a new patient
Book a room
Not AttributesAppointment.Time Pet.Name Owner.Telephone Room.Number
FOCUS ON
37. No Content Here
(Reserved for Watermark)
“The basic symptom of an Anemic Domain Model is
that at first blush it looks like the real thing. There are
objects, many named after the nouns in the domain
space, and these objects are connected with the rich
relationships and structure that true domain models
have.
The catch comes when you look at the behavior, and
you realize that there is hardly any behavior on these
objects, making them little more than bags of getters
and setters.”
—Martin Fowler
http://martinfowler.com/bliki/AnemicDomainModel.html
38. No Content Here
(Reserved for Watermark)
Many objects are not fundamentally defined by
their attributes, but rather by a thread of
continuity and identity.
—Eric Evans
Domain-Driven Design
39. No Content Here
(Reserved for Watermark)
Entities Have Identity & Are Mutable
Jan 12 10:00 am
Check-Up
Snickerdoodle
Appointment
ID=358
& Vaccinations
ID=172
XXXX 9:30 am
40. No Content Here
(Reserved for Watermark)
ENTITIES
Entities
in the
Navigation
Map
Evans,
Domain-Driven Design, p. 65
41. No Content Here
(Reserved for Watermark)
Entities should minimize direct access to their state (e.g. public property setters)
Encapsulate changes by exposing well-defined methods
Entities should be responsible for their own behavior
Be especially wary of collection properties!
EF Core 1.1+ supports encapsulation of properties (exposing IEnumerable or ReadOnlyCollection)
Encapsulation
42. No Content Here
(Reserved for Watermark)
Dependencies and Entities
Don’t inject dependencies into entity constructors
And of course don’t new up or call static infrastructure dependencies
This often leads to moving interesting behavior out of entities
and into services
Consider raising domain events
Behavior requiring dependencies shifts to domain event handlers
44. No Content Here
(Reserved for Watermark)
Value Object
Measures, quantifies, or describes a
thing in the domain.
Identity is based on composition of
values
Immutable
Compared using all values
No side effects
45. No Content Here
(Reserved for Watermark)
Value Object Example
Company Worth: $50,000,000
$ 50,000,000
Worth (Value Object)
Monetary Unit (string) “U.S. Dollar”
Amount (decimal): 50000000
Company (Entity)
ID (guid): 9F63CE8D-9F1E-45E0-85AB-C098CC15F8E6
Worth Unit (string): “US Dollar”
Worth Amount (decimal): 50000000
Company (Entity)
ID (guid): 9F63CE8D-9F1E-45E0-85AB-C098CC15F8E6
Worth
{
Source:http://fit.c2.com/wiki.cgi?WholeValue (Ward Cunningham)
46. No Content Here
(Reserved for Watermark)
DateTimeRange
public class DateTimeRange
{
public DateTimeRange(DateTime start, DateTime end)
{
Start=start;
End=end;
}
public DateTime Start { get; private set; }
public DateTime End { get; private set; }
…
}
Patient Appointment
10:00 am Jan 4, 2014 – 11:00 am Jan 4, 2014
Staff Meeting
2:00 pm Feb 1, 2014 – 3:15 pm Feb 1, 2014
47. No Content Here
(Reserved for Watermark)
It may surprise you to learn that we should strive
to model using Value Objects instead of Entities
wherever possible. Even when a domain concept
must be modeled as an Entity, the Entity’s design
should be biased toward serving as
a value container rather than a child Entity
container.
—Vaughn Vernon
Implementing Domain Driven Design
51. No Content Here
(Reserved for Watermark)
Aggregates
Customer
Address
Customer Aggregate
Product
Component
Product Aggregate
1
N N
1
Aggregate Root Aggregate Root
53. No Content Here
(Reserved for Watermark)
An aggregate is a cluster of associated objects
that we treat as a unit for the purpose of data
changes.
—Eric Evans
Domain-Driven Design
54. No Content Here
(Reserved for Watermark)
Important operations that don’t belong to a particular Entity or Value Object
Good Domain Services:
Not a natural part of an Entity or Value Object
Have an interface defined in terms of other domain model elements
Are stateless (but may have side effects)
Live in the Core of the application
Domain Services
Result
Value
Object
Entity
2
Entity
1
Service
55. No Content Here
(Reserved for Watermark)
Examples of Services in Different Layers
UI Layer
& Application Layer
InfrastructureDomain
(“Application Core”)
Message Sending
Message Processing
XML Parsing
UI Services
Transfer Between Accounts
Process Order
Send Email
Log to a File
56. No Content Here
(Reserved for Watermark)
Repository
Palaeoclimate archives: Core repository of AWI
Hannes Grobe/AWI
Creative Commons Attribution 3.0
57. No Content Here
(Reserved for Watermark)
A repository represents all objects of a certain
type as a conceptual set…like a collection with
more elaborate querying capability.
—Eric Evans
Domain-Driven Design
58. No Content Here
(Reserved for Watermark)
Repository
Benefits
Provides common abstraction for persistence
Promotes Separation of Concerns
Communicates Design Decisions
Enables Testability
Improved Maintainability
59. No Content Here
(Reserved for Watermark)
Client code can be ignorant of
repository implementation
…but developers cannot
N+1
Query Errors
Inappropriate
use of eager or
lazy loading
Fetching more
data than
required
Common Repository Blunders
60. No Content Here
(Reserved for Watermark)
Enforce proper Aggregate usage by only creating Repositories
for Aggregates
Use Marker Interfaces to identity Aggregate Roots
Constrain generic repository implementations to work with
Aggregate Root types only
Repositories and Aggregates
61. No Content Here
(Reserved for Watermark)
Avoid returning IQueryable results
Initially, use separate methods for specialized queries and commands
Address method explosion, SRP violation, and too much Repository complexity with
the Specification pattern
Repository Method Tips
62. No Content Here
(Reserved for Watermark)
Domain Events (one of my favorites)
Specification
Learn more about these from my Pluralsight courses:
• DDD Fundamentals
• Design Patterns Library
Also check out Jimmy Bogard’s DDD talk at 12:15 today in Nile
More Patterns (we don’t have time for)
63. No Content Here
(Reserved for Watermark)
Or tweet me @ardalis and I’ll answer
later.
Let me know if I can help your team
get up to speed with DDD, Clean
Architecture, and/or .NET Core.
Questions?
64. No Content Here
(Reserved for Watermark)
No Content Here
(Reserved for Watermark)
No Content Here
(Reserved for Course Previews)
Thanks!
Follow us:
/DevIQPage
DevIQ.com/updates
@deviq
• full-length courses
• samples
• member-only events
Enroll in DevIQ for access to:
DevIQ.com/enroll
Ardalis.com
@ardalis | steve@deviq.com
Steve Smith
66. No Content Here
(Reserved for Watermark)
Repositories ✓
Factories ✓
Services ✓
Entities ✓
Value Objects ✓
Aggregates ✓
Oh yeah, Domain Events
Usually the last kid picked from
the DDD patterns I’m right
here!
67. No Content Here
(Reserved for Watermark)
Domain Events not covered in original DDD book (2004)
Covered by Martin Fowler in 2005
Evans published article on them in 2010
Domain-Driven Design
68. No Content Here
(Reserved for Watermark)
Application Events
Page Load, Button Click, Window Scroll
System Events
Restart, Backup Completed
Domain Events
Appointment Confirmed, Checkout Completed, Analysis Finished
Kinds of Events
69. No Content Here
(Reserved for Watermark)
Given a customer has created an order
When the customer completes their purchase
Then the customer receives an email confirmation
An example scenario
70. No Content Here
(Reserved for Watermark)
OrderService
Checkout(Order order)
- Save pending order in database
- Send confirmation email
An example solution
72. No Content Here
(Reserved for Watermark)
Given a customer has created an order
When the customer completes their purchase
Then the customer’s card is charged
And if it fails, send a different message to the customer
Then inventory is checked to ensure the order can be fulfilled
And if not a different message is sent to the customer
More requirements
73. No Content Here
(Reserved for Watermark)
OrderService
Checkout(Order order)
oAttempt to process payment
oIf payment fails, send notification email; exit
oSave pending order in database
oConfirm inventory is available
oIf insufficient email, send notification email; exit
oSend successful order confirmation email
An example solution
74. No Content Here
(Reserved for Watermark)
Complexity is growing
Must change with each new requirement
Open/Closed Principle
Checkout’s responsibilities are growing
Single Responsibility Principle
Potentially different abstraction levels (emails, order processing rules)
Analysis
75. No Content Here
(Reserved for Watermark)
The Hollywood Principle
“Don’t Call Us, We’ll Call You”
See also Inversion of Control
Events allow other code to respond to something happening
Code initiating change doesn’t need to know about all follow-on activities
76. No Content Here
(Reserved for Watermark)
OrderService
Checkout(Order order)
- Dispatch new OrderCompletedEvent(order)
Event Handlers:
OrderPaymentHandler
OrderInventoryHandler
OrderNotificationHandler
An event-driven solution
77. No Content Here
(Reserved for Watermark)
An Event
Something that happened
…that other parts of the application may need to know about
It’s a message
…which should be immutable, since it represents the past
Usually asynchronous
…especially across process boundaries
Event-Driven Programming
78. No Content Here
(Reserved for Watermark)
Model something that happens which is of interest to a domain expert
May lead to (or result from) a state change in a domain object
Are part of the domain model
Are usually handled synchronously within the application (but may themselves raise
events outside of the application)
Domain Events
79. No Content Here
(Reserved for Watermark)
An event is raised
Handlers within the current process handle the event
If external applications need to be notified, specific handlers can adapt and send
events to these applications as well
If unknown or future external applications will need to respond to events, a service
bus can be implemented
Event Processing
80. No Content Here
(Reserved for Watermark)
How do you add logic to entities that affects multiple entities?
Example:
When a customer’s total amount purchased exceeds $1000, notify a salesperson to
contact them.
Common Scenario
81. No Content Here
(Reserved for Watermark)
How do you add logic to entities that affects multiple entities?
Don’t solve this by using Dependency Injection on your entities. You should be able to
easily instantiate entities without dependencies.
Avoid: Injecting Dependencies into Entities
82. No Content Here
(Reserved for Watermark)
How do you add logic to entities that affects multiple entities?
Don’t move logic that belongs within an entity into a service just because other
entities are interested in what’s happening. This leads to the anemic domain model
antipattern.
Only do this if the behavior spans multiple aggregates, in which case, the logic doesn’t
belong to a particular entity or aggregate.
Avoid: Shifting Entity logic to Services
83. No Content Here
(Reserved for Watermark)
How do you add logic to entities that affects multiple entities?
Raise a domain event to represent the action that took place.
Handle the domain event in a handler that collaborates with other entities.
Alternately, have the Aggregate Root register for events raised by members of its
Aggregate.
Use Domain Events (and perhaps Aggregates)