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.
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.
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
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
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
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
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
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
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
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
Notes de l'éditeur
Підхід для розробки ПЗ в складній предментій галузі, який заключається в розробці базуючись на предментній моделі реального світу
Це дає можливість аналізувати бізнес логіку і відповідність її до моделі реального світу і до вимог до програмного забезпечення
Це приводить нас до розмови про збір вимог до ПЗ
Через те, що замовник і розробник не зрозуміли одного, в ПЗ виявили дефекти
Хто найкраще розкаже про вимоги до ПЗ? Хто найкраще знає проблеми, які виникають в цій предметній області? Експерти предметної області, доменні експерти згідно термінології DDD. Проте як говорити з ними???
Спільна мова, однозначна мова Однозначність – наприклад, обидві сторони повинні розуміти, що висота і швидкість польоту задаються в flight plan, not in route
Грецький філософ Анаксімандер створив карту, яка виглядала приблизно так. Вона містить уявлення про будову світу (ойкумена). Річка Фазіс – це річка Ріоні в Грузії Вона неточна – форма материків, материки, річки ітд. Це модель світу – спрощене представлення знаннь певної предметної області (географія).
Це інша модель тієї ж предметної області, яка називається проекція Меркатора. Вона має таку властивість, що пряма лінія між двома точками може бути дуже просто перенесена в реальний світ як курс корабля, дуже легко прокладати навігацію користуючись цією картою. Очевидно що ця модель є точніша і повніша за попередню. Чи є вона краща за попередню? Дивлячись для чого. Ми маємо 2 різні моделі одної й тої ж предметної області. Оскільки для них були різні вимоги (і технічні можливості), ми отримали зовсім різні моделі
Entity – обєкт який цікавить нас не як набір своїх атрибутів, а як конкретний інстанс, який має свій lifecycle, і свою ідентичність. Дві ентіті з однаковими атрибутами – це дві різні бізнес-сутності Для кожної entity можна визначити свій ключ який буде унікальним – або з реального світу, або ж surrogate key
VO нас цікавлять тільки як набір своїх атрибутів. Два VO з однаковими атрибутами – це одна і та сама бізнес-сутність
Коли ви керуєте автомобілем, ви не думаєте про те, що треба крутити колеса, чи двигун повинен підпалювати пари бензину іскрою – ви просто керуєте автомобілем. В цьому контексті автомобіль – це агрегат кількох об»єктів і служить як aggregate root . Виділивши кілька агрегатів, можна сильно спростити структуру звязків ДМоделі
Агрегат рут виступає як API, як entry point для всього агрегата, зменшуючи coupling системи , її звязність
Сервіс служить як холдер для поведінки, яка не є частиною поведінки якоїсь конкретної entity. Сервіс не обовязково представляти як обєкт, його можна представляти як неймспейс для процедур/функцій, тому що він не має стану
UI(presentation) – відповідальний за презентацію інформації користувачам і інтерпретацію команд користувача Application – тонкий леєр який координує поведінку програми. Він не містить бізнес логіки, не зберігає стану бізнес-обєктів, але може зберігати стан прогресу якоїсь задачі Domain – містить інформацію про предметну область Infrastructure – supporting library. Надає комунікацію між рівнями, перзістенс, UI libraries etc