SlideShare une entreprise Scribd logo
1  sur  40
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

Contenu connexe

En vedette (20)

漫谈php和java
漫谈php和java漫谈php和java
漫谈php和java
 
RCMSL Phenomenal Aug 28, 2009
RCMSL Phenomenal Aug 28, 2009RCMSL Phenomenal Aug 28, 2009
RCMSL Phenomenal Aug 28, 2009
 
Postcards From Pure Michigan
Postcards From Pure MichiganPostcards From Pure Michigan
Postcards From Pure Michigan
 
Farma
FarmaFarma
Farma
 
Angeiologie 4 2013 - 1-2014 livre des resumes
Angeiologie 4 2013 - 1-2014 livre des resumesAngeiologie 4 2013 - 1-2014 livre des resumes
Angeiologie 4 2013 - 1-2014 livre des resumes
 
007 014 belcaro corrige
007 014 belcaro corrige007 014 belcaro corrige
007 014 belcaro corrige
 
201010 SPLASH Tutorial
201010 SPLASH Tutorial201010 SPLASH Tutorial
201010 SPLASH Tutorial
 
VU 19 Nov 09
VU 19  Nov 09VU 19  Nov 09
VU 19 Nov 09
 
Thomasville
ThomasvilleThomasville
Thomasville
 
Accomplishment, Aspirations & Challenges: Boston
Accomplishment, Aspirations & Challenges: BostonAccomplishment, Aspirations & Challenges: Boston
Accomplishment, Aspirations & Challenges: Boston
 
Monaco 020909
Monaco 020909Monaco 020909
Monaco 020909
 
Barya Perception
Barya PerceptionBarya Perception
Barya Perception
 
Uip Romain
Uip RomainUip Romain
Uip Romain
 
RCMSL Phenomenal July 16, 2009
RCMSL Phenomenal July 16, 2009RCMSL Phenomenal July 16, 2009
RCMSL Phenomenal July 16, 2009
 
201106 WICSA
201106 WICSA201106 WICSA
201106 WICSA
 
Week5-Group-J
Week5-Group-JWeek5-Group-J
Week5-Group-J
 
Contention
ContentionContention
Contention
 
링크의 경제학(요약)
링크의 경제학(요약)링크의 경제학(요약)
링크의 경제학(요약)
 
Eeuwigblijvenleren
EeuwigblijvenlerenEeuwigblijvenleren
Eeuwigblijvenleren
 
Eddie Slide Show
Eddie Slide ShowEddie Slide Show
Eddie Slide Show
 

Similaire à Domain driven design

Refreshing Domain Driven Design
Refreshing Domain Driven DesignRefreshing Domain Driven Design
Refreshing Domain Driven DesignAndré Borgonovo
 
Domain Driven Design Big Picture Strategic Patterns
Domain Driven Design Big Picture Strategic PatternsDomain Driven Design Big Picture Strategic Patterns
Domain Driven Design Big Picture Strategic PatternsMark Windholtz
 
Communications is distributed systems
Communications is distributed systemsCommunications is distributed systems
Communications is distributed systemsSHATHAN
 
Oracle ADF Architecture TV - Development - Naming Conventions & Project Layouts
Oracle ADF Architecture TV - Development - Naming Conventions & Project LayoutsOracle ADF Architecture TV - Development - Naming Conventions & Project Layouts
Oracle ADF Architecture TV - Development - Naming Conventions & Project LayoutsChris Muir
 
Distributing computing.pptx
Distributing computing.pptxDistributing computing.pptx
Distributing computing.pptxKaviya452563
 
Mrpro(tm) Records-Effective Records, Analysis and Metrics
Mrpro(tm) Records-Effective Records, Analysis and MetricsMrpro(tm) Records-Effective Records, Analysis and Metrics
Mrpro(tm) Records-Effective Records, Analysis and Metricsjagada7
 
chapter 5.pptx
chapter 5.pptxchapter 5.pptx
chapter 5.pptxWantey
 
Best practices for application migration to public clouds interop presentation
Best practices for application migration to public clouds interop presentationBest practices for application migration to public clouds interop presentation
Best practices for application migration to public clouds interop presentationesebeus
 
Microservice at a glance
Microservice at a glanceMicroservice at a glance
Microservice at a glanceKetan Ghumatkar
 
PPT_CLOUD COMPUTING_UNIT 1.pptx.pdf
PPT_CLOUD COMPUTING_UNIT 1.pptx.pdfPPT_CLOUD COMPUTING_UNIT 1.pptx.pdf
PPT_CLOUD COMPUTING_UNIT 1.pptx.pdfVineet446350
 
UNIT4_ESD_wfffffggggggggggggith_ARM.pptx
UNIT4_ESD_wfffffggggggggggggith_ARM.pptxUNIT4_ESD_wfffffggggggggggggith_ARM.pptx
UNIT4_ESD_wfffffggggggggggggith_ARM.pptxrealme6igamerr
 
Lecture 11 - distributed database
Lecture 11 - distributed databaseLecture 11 - distributed database
Lecture 11 - distributed databaseHoneySah
 
IRJET- An Overview on Cloud Computing and Challenges
IRJET-  	  An Overview on Cloud Computing and ChallengesIRJET-  	  An Overview on Cloud Computing and Challenges
IRJET- An Overview on Cloud Computing and ChallengesIRJET Journal
 

Similaire à Domain driven design (20)

Refreshing Domain Driven Design
Refreshing Domain Driven DesignRefreshing Domain Driven Design
Refreshing Domain Driven Design
 
Domain Driven Design Big Picture Strategic Patterns
Domain Driven Design Big Picture Strategic PatternsDomain Driven Design Big Picture Strategic Patterns
Domain Driven Design Big Picture Strategic Patterns
 
Communications is distributed systems
Communications is distributed systemsCommunications is distributed systems
Communications is distributed systems
 
ITM711-M2.pdf
ITM711-M2.pdfITM711-M2.pdf
ITM711-M2.pdf
 
ITM711 M2.pdf
ITM711  M2.pdfITM711  M2.pdf
ITM711 M2.pdf
 
Oracle ADF Architecture TV - Development - Naming Conventions & Project Layouts
Oracle ADF Architecture TV - Development - Naming Conventions & Project LayoutsOracle ADF Architecture TV - Development - Naming Conventions & Project Layouts
Oracle ADF Architecture TV - Development - Naming Conventions & Project Layouts
 
Distributing computing.pptx
Distributing computing.pptxDistributing computing.pptx
Distributing computing.pptx
 
Mrpro(tm) Records-Effective Records, Analysis and Metrics
Mrpro(tm) Records-Effective Records, Analysis and MetricsMrpro(tm) Records-Effective Records, Analysis and Metrics
Mrpro(tm) Records-Effective Records, Analysis and Metrics
 
chapter 5.pptx
chapter 5.pptxchapter 5.pptx
chapter 5.pptx
 
Clean sw 3_architecture
Clean sw 3_architectureClean sw 3_architecture
Clean sw 3_architecture
 
Best practices for application migration to public clouds interop presentation
Best practices for application migration to public clouds interop presentationBest practices for application migration to public clouds interop presentation
Best practices for application migration to public clouds interop presentation
 
Comet Cloud
Comet CloudComet Cloud
Comet Cloud
 
Microservice at a glance
Microservice at a glanceMicroservice at a glance
Microservice at a glance
 
PPT_CLOUD COMPUTING_UNIT 1.pptx.pdf
PPT_CLOUD COMPUTING_UNIT 1.pptx.pdfPPT_CLOUD COMPUTING_UNIT 1.pptx.pdf
PPT_CLOUD COMPUTING_UNIT 1.pptx.pdf
 
UNIT4_ESD_wfffffggggggggggggith_ARM.pptx
UNIT4_ESD_wfffffggggggggggggith_ARM.pptxUNIT4_ESD_wfffffggggggggggggith_ARM.pptx
UNIT4_ESD_wfffffggggggggggggith_ARM.pptx
 
Introduction to DDD
Introduction to DDDIntroduction to DDD
Introduction to DDD
 
CLOUD STORAGE.pptx
CLOUD STORAGE.pptxCLOUD STORAGE.pptx
CLOUD STORAGE.pptx
 
Lecture 11 - distributed database
Lecture 11 - distributed databaseLecture 11 - distributed database
Lecture 11 - distributed database
 
Security in cloud computing
Security in cloud computingSecurity in cloud computing
Security in cloud computing
 
IRJET- An Overview on Cloud Computing and Challenges
IRJET-  	  An Overview on Cloud Computing and ChallengesIRJET-  	  An Overview on Cloud Computing and Challenges
IRJET- An Overview on Cloud Computing and Challenges
 

Dernier

08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 

Dernier (20)

08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 

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

Notes de l'éditeur

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