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

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-drivendesign (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 toisolate business logic from other parts application source code
  • 5.
    What to do? Useinheritance 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.
  • 6.
  • 7.
    Non-developers hear thesame when you talk to them You hear the same when non- developers talk to you
  • 8.
  • 9.
  • 10.
    Who knows thedomain? Domain experts do! Talk to them
  • 11.
    How to talkto 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.
  • 13.
  • 14.
    Domain model shouldnot 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
  • 15.
  • 16.
    Entities Entity is anobject, 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 • Entitiesare 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 Objectis 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 Whatif domain is too big and complex? Too many relations? 03/29/13 21
  • 22.
    Aggregate A collection ofobjects 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 behaviorwhich 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.
  • 27.
    You all knowthat • 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 allthe 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.
  • 30.
    Cargo example • Customercan ship a cargo from source to destination • Route can be changed on it’s way Footer Text 03/29/13 30
  • 31.
    Cargo example • Serviceshould 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 advisedto 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 badcode from good code. Point. 03/29/13 34
  • 35.
    Distillation Look at yourfeatures/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 andauthorization •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 Iuse 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.
  • 40.
    Links http://habrahabr.ru/post/61524/ Russian, alot 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