SlideShare a Scribd company logo
Domain Driven
   Design
   presenter: Yuriy Taras



                            03/29/13   1
Agenda
•   What and Why?
•   Requirements
•   Building blocks
•   Higher level patterns




                              03/29/13   2
What is DDD?
Domain-driven design (DDD) is an approach to
develop software for complex needs by connecting
the implementation to an evolving model




                                             03/29/13   3
Why?
DDD helps to isolate business logic from other parts
  application source code
What to do?
Use inheritance from base class to provide ad-hoc
  polymorphism and use monadic transformation to
  extract iterator interface, so strategy pattern can
  be applied to persistence level from MVC
  prospective.
Understood?



    No!
Non-developers hear the same
    when you talk to them
You hear the same when non-
    developers talk to you
Talking about requirements
Misunderstanding is a
bug




                        03/29/13   9
Who knows the domain?
      Domain experts do!




         Talk to them
How to talk to them?
Ubiquitous Language!

All traffic is made up of planes. Each plane takes off
from a departure place, and lands at a destination
place.
The pilots receive a route they must follow. And they
should stay on that route as close as possible.
Before leaving the airport, the pilots receive a
detailed flight plan which includes all sorts of
information about the flight: the route, cruise altitude,
the cruise speed, the type of airplane, even
information about the crew members.
Anaximander world map




                   03/29/13   12
Mercator projection




                      03/29/13   13
Domain model should not be strict or realistic. Instead
domain model should focus on what’s important in
current context and omit what’s not.




                                                          03/29/13
                                                            14
Building blocks
Entities
Entity is an object, which has an identity which
remains the same throughout the states of the
software. Each Entity can be strictly identified by it’s
identity
Example:
•US citizen – Social Security number
•Bank account – account number
•Meeting – surrogate key




                                                     03/29/13   16
Entity implementation
• Entities are considered equal if their identity are
  equal
• Entities should stay focused on domain level, don’t
  put infrastructure code or code which belongs to
  other entities into them
• Entities can provide getters/readers
• Don’t provide setters for your entities, provide
  business mutators instead:
   o post.status = PUBLISHED # BAD
   o post.publish() # GOOD




                                                 03/29/13   17
CQS
Use Command-Query Separation (not CQRS) – each
method is either a command or query:
!post.publish()
!user.disable()
!order.add_line_item(product, 2)
?order.get_price
?post.get_publish_date




                                          03/29/13   18
Value object
Value Object is an object which is used to describe
certain aspects of a domain but doesn’t have an
identity.
Example:
•Address
•Money amount
•2D/3D Point




                                                03/29/13   19
Value object
          implementation
• Value objects should be immutable – it makes them
  shareable
• Value objects can contain other VO’s and even
  Entities




                                              03/29/13   20
Complex Domain Model
What if domain
is too big and
complex? Too
many relations?




                   03/29/13   21
Aggregate
A collection of objects that are bound together by a
root Entity, otherwise known as an Aggregate Root.
Example:
•Order contains line items
•Car contains wheels and engine
•Blog post contains comments*
•Cinema contains seats

* it depends


                                                03/29/13   22
Aggregate
          implementation
• All Aggregate Entities should be accessible only
  from Aggregate Root
• Reference to internal Entities may be passed to
  external object, but those can use it only temporary
  and can’t store it
• Internal Entity identity doesn’t have to be unique
  across the application, uniqueness across the
  Aggregate is enough




                                                03/29/13   23
Example
Customer


            1




            *


Order




Line item
                1   1   Product




                                  03/29/13   24
Service
Services contain behavior which can’t be considered
as a part of specific entity.
Example:
•Transaction Service transfers money from one
account to another
•Payment Service processes orders
•Route Service provides routes based on route
specification
Services should be stateless.
Don’t mix infrastructure and domain services!

                                              03/29/13   25
Layered architecture




                       03/29/13   26
You all know that
• Modules are groups of elements which are
  functionally or logically belong together
• Factories are used to create Entities and
  Aggregates*

* Factories are not necessary separate objects, it can
   be GoF Factory Method or Builder or whatever




                                                 03/29/13   27
Repository
Repositories encapsulate all the logic needed to
obtain object references.
Note that even if repository implementation can
belong to infrastructure layer, it’s API is a pure domain
model
Example:
•customer_repository.add_customer(customer)
•customer_repository.find_customer(‘12345’)
If we have separate repository for Aggregate Entities,
only Aggregate Root (or it’s repository) should use
them

                                                   03/29/13   28
Higher level patterns



Footer Text                           03/29/13   29
Cargo example
• Customer can ship a cargo from source to
  destination
• Route can be changed on it’s way




Footer Text                                  03/29/13   30
Cargo example
• Service should provide either cheapest or fastest
  route based on customer’s preferences




 Footer Text                                     03/29/13   31
Bounded contexts

               Transition   Edge
Cargo
                                   *

        1                          *


        1                   Node

Route

        1

        *


Leg




                                       03/29/13   32
Bounded Context
It’s advised to maintain Translation Map, which shows
bound contexts and relationships between them
Bounded Contexts names should be part of the
Ubiquitous Language
Bonded Contexts can be used for team organization
Contexts can relate to each other using Shared
Kernel, Customer-Supplier or Conformist patterns




                                                03/29/13   33
Anticorruption layer
Isolate bad code from good code. Point.




                                          03/29/13   34
Distillation
Look at your features/use cases/concepts and
separate them into 3 parts:
•Core Domain
•Supporting subdomain
•Generic Subdomain




Footer Text                                    03/29/13   35
Generic subdomains
Examples:
•Authentication and authorization
•Mailing*
•Reporting*
You can:
•Buy it
•Outsource it
•Copy it from existing projects
•Implement it
* it depends

                                    03/29/13   36
Core and supporting
           domain
Supporting is what we have to have.
Core domain is what differentiate us.
Supporting can be crap.
Core can’t.




                                        03/29/13   37
When should I use DDD?
• When I have complex business logic. It’s not suited
  for your mom’s CRUD app
• When I have access to domain experts – otherwise I
  will build other perfect but useless app
• When I have skilled team




 Footer Text                                   03/29/13   38
Questions?



Footer Text                03/29/13   39
Links
http://habrahabr.ru/post/61524/ Russian, a lot of links
http://www.infoq.com/minibooks/domain-driven-
design-quickly English, free book
http://dddcommunity.org/ English, community




                                                  03/29/13   40

More Related Content

PPTX
CQRS introduction
PPT
LiveOffice Email Archiving Makes Cents
PPT
Financial planning introduction fall 2010
PDF
Biopython at BOSC 2010
PDF
PDF
201005 accelerometer and core Location
PDF
Week10
PDF
Windowsxp
CQRS introduction
LiveOffice Email Archiving Makes Cents
Financial planning introduction fall 2010
Biopython at BOSC 2010
201005 accelerometer and core Location
Week10
Windowsxp

Viewers also liked (20)

PPT
漫谈php和java
PDF
RCMSL Phenomenal Aug 28, 2009
PDF
Postcards From Pure Michigan
PDF
Angeiologie 4 2013 - 1-2014 livre des resumes
PDF
007 014 belcaro corrige
PDF
201010 SPLASH Tutorial
PPT
VU 19 Nov 09
PDF
Thomasville
PDF
Accomplishment, Aspirations & Challenges: Boston
PPT
Monaco 020909
PPT
Barya Perception
PPT
Uip Romain
PDF
RCMSL Phenomenal July 16, 2009
PDF
PDF
Week5-Group-J
PPT
Contention
PPT
링크의 경제학(요약)
PPTX
Eeuwigblijvenleren
PPT
Eddie Slide Show
漫谈php和java
RCMSL Phenomenal Aug 28, 2009
Postcards From Pure Michigan
Angeiologie 4 2013 - 1-2014 livre des resumes
007 014 belcaro corrige
201010 SPLASH Tutorial
VU 19 Nov 09
Thomasville
Accomplishment, Aspirations & Challenges: Boston
Monaco 020909
Barya Perception
Uip Romain
RCMSL Phenomenal July 16, 2009
Week5-Group-J
Contention
링크의 경제학(요약)
Eeuwigblijvenleren
Eddie Slide Show
Ad

Similar to Domain driven design (20)

PPTX
Refreshing Domain Driven Design
PDF
Domain Driven Design Big Picture Strategic Patterns
PPT
Communications is distributed systems
PDF
ITM711-M2.pdf
PDF
ITM711 M2.pdf
PDF
Oracle ADF Architecture TV - Development - Naming Conventions & Project Layouts
PPTX
Distributing computing.pptx
PPT
Mrpro(tm) Records-Effective Records, Analysis and Metrics
PPTX
chapter 5.pptx
PPTX
Clean sw 3_architecture
PPTX
Best practices for application migration to public clouds interop presentation
PPT
Comet Cloud
PPTX
selected topics in CS-CHaapteeer three.pptx
PPTX
Microservice at a glance
PPTX
c.cloudstorage-221115133653-fef605c2.pptx
PDF
cc_unit3_SMCE.pdf Cloud Computing Unit-3
PDF
PPT_CLOUD COMPUTING_UNIT 1.pptx.pdf
PPTX
WSO2Con 2025 - Architecting Cloud-Native Applications
PPTX
Cloud computing is the delivery of computing services—including servers, stor...
PPTX
UNIT4_ESD_wfffffggggggggggggith_ARM.pptx
Refreshing Domain Driven Design
Domain Driven Design Big Picture Strategic Patterns
Communications is distributed systems
ITM711-M2.pdf
ITM711 M2.pdf
Oracle ADF Architecture TV - Development - Naming Conventions & Project Layouts
Distributing computing.pptx
Mrpro(tm) Records-Effective Records, Analysis and Metrics
chapter 5.pptx
Clean sw 3_architecture
Best practices for application migration to public clouds interop presentation
Comet Cloud
selected topics in CS-CHaapteeer three.pptx
Microservice at a glance
c.cloudstorage-221115133653-fef605c2.pptx
cc_unit3_SMCE.pdf Cloud Computing Unit-3
PPT_CLOUD COMPUTING_UNIT 1.pptx.pdf
WSO2Con 2025 - Architecting Cloud-Native Applications
Cloud computing is the delivery of computing services—including servers, stor...
UNIT4_ESD_wfffffggggggggggggith_ARM.pptx
Ad

Recently uploaded (20)

PPTX
A Presentation on Artificial Intelligence
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PPTX
Cloud computing and distributed systems.
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
cuic standard and advanced reporting.pdf
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
Spectroscopy.pptx food analysis technology
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Approach and Philosophy of On baking technology
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Empathic Computing: Creating Shared Understanding
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
A Presentation on Artificial Intelligence
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Cloud computing and distributed systems.
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Spectral efficient network and resource selection model in 5G networks
A comparative analysis of optical character recognition models for extracting...
cuic standard and advanced reporting.pdf
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Chapter 3 Spatial Domain Image Processing.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
MYSQL Presentation for SQL database connectivity
Spectroscopy.pptx food analysis technology
Reach Out and Touch Someone: Haptics and Empathic Computing
Approach and Philosophy of On baking technology
Building Integrated photovoltaic BIPV_UPV.pdf
Empathic Computing: Creating Shared Understanding
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Profit Center Accounting in SAP S/4HANA, S4F28 Col11

Domain driven design

  • 1. Domain Driven Design presenter: Yuriy Taras 03/29/13 1
  • 2. Agenda • What and Why? • Requirements • Building blocks • Higher level patterns 03/29/13 2
  • 3. What is DDD? Domain-driven design (DDD) is an approach to develop software for complex needs by connecting the implementation to an evolving model 03/29/13 3
  • 4. Why? DDD helps to isolate business logic from other parts application source code
  • 5. What to do? Use inheritance from base class to provide ad-hoc polymorphism and use monadic transformation to extract iterator interface, so strategy pattern can be applied to persistence level from MVC prospective.
  • 7. Non-developers hear the same when you talk to them You hear the same when non- developers talk to you
  • 10. Who knows the domain? Domain experts do! Talk to them
  • 11. How to talk to them? Ubiquitous Language! All traffic is made up of planes. Each plane takes off from a departure place, and lands at a destination place. The pilots receive a route they must follow. And they should stay on that route as close as possible. Before leaving the airport, the pilots receive a detailed flight plan which includes all sorts of information about the flight: the route, cruise altitude, the cruise speed, the type of airplane, even information about the crew members.
  • 12. Anaximander world map 03/29/13 12
  • 13. Mercator projection 03/29/13 13
  • 14. Domain model should not be strict or realistic. Instead domain model should focus on what’s important in current context and omit what’s not. 03/29/13 14
  • 16. Entities Entity is an object, which has an identity which remains the same throughout the states of the software. Each Entity can be strictly identified by it’s identity Example: •US citizen – Social Security number •Bank account – account number •Meeting – surrogate key 03/29/13 16
  • 17. Entity implementation • Entities are considered equal if their identity are equal • Entities should stay focused on domain level, don’t put infrastructure code or code which belongs to other entities into them • Entities can provide getters/readers • Don’t provide setters for your entities, provide business mutators instead: o post.status = PUBLISHED # BAD o post.publish() # GOOD 03/29/13 17
  • 18. CQS Use Command-Query Separation (not CQRS) – each method is either a command or query: !post.publish() !user.disable() !order.add_line_item(product, 2) ?order.get_price ?post.get_publish_date 03/29/13 18
  • 19. Value object Value Object is an object which is used to describe certain aspects of a domain but doesn’t have an identity. Example: •Address •Money amount •2D/3D Point 03/29/13 19
  • 20. Value object implementation • Value objects should be immutable – it makes them shareable • Value objects can contain other VO’s and even Entities 03/29/13 20
  • 21. Complex Domain Model What if domain is too big and complex? Too many relations? 03/29/13 21
  • 22. Aggregate A collection of objects that are bound together by a root Entity, otherwise known as an Aggregate Root. Example: •Order contains line items •Car contains wheels and engine •Blog post contains comments* •Cinema contains seats * it depends 03/29/13 22
  • 23. Aggregate implementation • All Aggregate Entities should be accessible only from Aggregate Root • Reference to internal Entities may be passed to external object, but those can use it only temporary and can’t store it • Internal Entity identity doesn’t have to be unique across the application, uniqueness across the Aggregate is enough 03/29/13 23
  • 24. Example Customer 1 * Order Line item 1 1 Product 03/29/13 24
  • 25. Service Services contain behavior which can’t be considered as a part of specific entity. Example: •Transaction Service transfers money from one account to another •Payment Service processes orders •Route Service provides routes based on route specification Services should be stateless. Don’t mix infrastructure and domain services! 03/29/13 25
  • 26. Layered architecture 03/29/13 26
  • 27. You all know that • Modules are groups of elements which are functionally or logically belong together • Factories are used to create Entities and Aggregates* * Factories are not necessary separate objects, it can be GoF Factory Method or Builder or whatever 03/29/13 27
  • 28. Repository Repositories encapsulate all the logic needed to obtain object references. Note that even if repository implementation can belong to infrastructure layer, it’s API is a pure domain model Example: •customer_repository.add_customer(customer) •customer_repository.find_customer(‘12345’) If we have separate repository for Aggregate Entities, only Aggregate Root (or it’s repository) should use them 03/29/13 28
  • 29. Higher level patterns Footer Text 03/29/13 29
  • 30. Cargo example • Customer can ship a cargo from source to destination • Route can be changed on it’s way Footer Text 03/29/13 30
  • 31. Cargo example • Service should provide either cheapest or fastest route based on customer’s preferences Footer Text 03/29/13 31
  • 32. Bounded contexts Transition Edge Cargo * 1 * 1 Node Route 1 * Leg 03/29/13 32
  • 33. Bounded Context It’s advised to maintain Translation Map, which shows bound contexts and relationships between them Bounded Contexts names should be part of the Ubiquitous Language Bonded Contexts can be used for team organization Contexts can relate to each other using Shared Kernel, Customer-Supplier or Conformist patterns 03/29/13 33
  • 34. Anticorruption layer Isolate bad code from good code. Point. 03/29/13 34
  • 35. Distillation Look at your features/use cases/concepts and separate them into 3 parts: •Core Domain •Supporting subdomain •Generic Subdomain Footer Text 03/29/13 35
  • 36. Generic subdomains Examples: •Authentication and authorization •Mailing* •Reporting* You can: •Buy it •Outsource it •Copy it from existing projects •Implement it * it depends 03/29/13 36
  • 37. Core and supporting domain Supporting is what we have to have. Core domain is what differentiate us. Supporting can be crap. Core can’t. 03/29/13 37
  • 38. When should I use DDD? • When I have complex business logic. It’s not suited for your mom’s CRUD app • When I have access to domain experts – otherwise I will build other perfect but useless app • When I have skilled team Footer Text 03/29/13 38
  • 39. Questions? Footer Text 03/29/13 39
  • 40. Links http://habrahabr.ru/post/61524/ Russian, a lot of links http://www.infoq.com/minibooks/domain-driven- design-quickly English, free book http://dddcommunity.org/ English, community 03/29/13 40

Editor's Notes

  • #4: Підхід для розробки ПЗ в складній предментій галузі, який заключається в розробці базуючись на предментній моделі реального світу
  • #5: Це дає можливість аналізувати бізнес логіку і відповідність її до моделі реального світу і до вимог до програмного забезпечення
  • #9: Це приводить нас до розмови про збір вимог до ПЗ
  • #10: Через те, що замовник і розробник не зрозуміли одного, в ПЗ виявили дефекти
  • #11: Хто найкраще розкаже про вимоги до ПЗ? Хто найкраще знає проблеми, які виникають в цій предметній області? Експерти предметної області, доменні експерти згідно термінології DDD. Проте як говорити з ними???
  • #12: Спільна мова, однозначна мова Однозначність – наприклад, обидві сторони повинні розуміти, що висота і швидкість польоту задаються в flight plan, not in route
  • #13: Грецький філософ Анаксімандер створив карту, яка виглядала приблизно так. Вона містить уявлення про будову світу (ойкумена). Річка Фазіс – це річка Ріоні в Грузії Вона неточна – форма материків, материки, річки ітд. Це модель світу – спрощене представлення знаннь певної предметної області (географія).
  • #14: Це інша модель тієї ж предметної області, яка називається проекція Меркатора. Вона має таку властивість, що пряма лінія між двома точками може бути дуже просто перенесена в реальний світ як курс корабля, дуже легко прокладати навігацію користуючись цією картою. Очевидно що ця модель є точніша і повніша за попередню. Чи є вона краща за попередню? Дивлячись для чого. Ми маємо 2 різні моделі одної й тої ж предметної області. Оскільки для них були різні вимоги (і технічні можливості), ми отримали зовсім різні моделі
  • #17: Entity – обєкт який цікавить нас не як набір своїх атрибутів, а як конкретний інстанс, який має свій lifecycle, і свою ідентичність. Дві ентіті з однаковими атрибутами – це дві різні бізнес-сутності Для кожної entity можна визначити свій ключ який буде унікальним – або з реального світу, або ж surrogate key
  • #20: VO нас цікавлять тільки як набір своїх атрибутів. Два VO з однаковими атрибутами – це одна і та сама бізнес-сутність
  • #23: Коли ви керуєте автомобілем, ви не думаєте про те, що треба крутити колеса, чи двигун повинен підпалювати пари бензину іскрою – ви просто керуєте автомобілем. В цьому контексті автомобіль – це агрегат кількох об»єктів і служить як aggregate root . Виділивши кілька агрегатів, можна сильно спростити структуру звязків ДМоделі
  • #24: Агрегат рут виступає як API, як entry point для всього агрегата, зменшуючи coupling системи , її звязність
  • #26: Сервіс служить як холдер для поведінки, яка не є частиною поведінки якоїсь конкретної entity. Сервіс не обовязково представляти як обєкт, його можна представляти як неймспейс для процедур/функцій, тому що він не має стану
  • #27: UI(presentation) – відповідальний за презентацію інформації користувачам і інтерпретацію команд користувача Application – тонкий леєр який координує поведінку програми. Він не містить бізнес логіки, не зберігає стану бізнес-обєктів, але може зберігати стан прогресу якоїсь задачі Domain – містить інформацію про предметну область Infrastructure – supporting library. Надає комунікацію між рівнями, перзістенс, UI libraries etc