Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

D2 domain driven-design

1,967 views

Published on

DomainDrivenDesign ValueObject Aggregates Entities Domain SOLID DDD CQRS Persistence Factory Services Delphi OpenSource mORMot

Published in: Software
  • Be the first to comment

D2 domain driven-design

  1. 1. Software Architecture & Design  Architecture  From n-Tier to SOA  From SOAP to REST  Technical Debt  Design  From SQL to ORM, NoSQL and ODM  From RAD to MVC  SOLID principles  Domain Driven Design (DDD) Applying patterns on Delphi code using mORMot Software Architecture & Design
  2. 2. Domain Driven Design
  3. 3. Domain Driven Design (DDD)  Is DDD good for you?  Modeling your objects  Patterns  Architecture  practice Domain Driven Design
  4. 4. Domain Driven Design Domain Driven Design  Sounds pretty much nice and easy
  5. 5. Domain Driven Design Domain Driven Design Model-Driven Design Ubiquitous Language define model with Bounded Contexts identify scope with Services process model with Entities express model with Value Objects express model with Clean/Layered/ Hexagonal Architecture isolate domain with Events express state changes with RAD exclude Repositories access with Aggregates encapsulate with Factories instantiated by encapsulate with instantiated by access with instantiated by
  6. 6. Domain Driven Design  Focus on the Domain  Define Bounded contexts within this domain  Create an evolving Model of the domain  Use Ubiquitous Language in model and code  Identify objects: Values, Entities, Aggregates  Publish the domain as well-defined Services  Isolate the domain from other kind of concern  Uncouple from implementation details  Integrate the domain services with existing Domain Driven Design
  7. 7. DDD pre-requisites  Identified and well-bounded domain  e.g. your business target should be clearly identified  Access to domain experts  need iterative creative collaboration  Skilled team, able to write clean code  more about code expressiveness than technology  You want your internal team to accumulate knowledge of the domain  therefore, outsourcing may be constrained to applications, not the core domain Domain Driven Design
  8. 8. Role of Patterns  In your code: once: it’s a fluke, twice: its coincidence, three times: it’s a Pattern!  Discovered (observed), not invented  Except for their name   Elevate effectiveness of our communication  A ‘shorthand’ for more complex ideas Domain Driven Design
  9. 9. DDD: the premise  Writing software is actually straightforward  Determining what to write is hard!  The Key to success is understanding the Problem Domain intimately  Not to use the latest shiny technology Domain Driven Design
  10. 10. Check your concerns  You have a specific problem to solve  Your goal is identified , but your business is exploring  You do not know how to accomplish your goal  You need to bring clarity, and solve inner complexity  e.g. modeling a lot of rules  DDD is not to build simple applications – RAD is there  DDD meets your strategic goals  DDD is to be used where you will get your business money, and make you distinctive from your competitors  You don't have all of these, but at least one or two Domain Driven Design
  11. 11. Domain Driven Design Domain Driven Design Model-Driven Design Ubiquitous Language define model with Bounded Contexts identify scope with Services process model with Entities express model with Value Objects express model with Clean/Layered/ Hexagonal Architecture isolate domain with Events express state changes with RAD exclude Repositories access with Aggregates encapsulate with Factories instantiated by encapsulate with instantiated by access with instantiated by
  12. 12. Ubiquitous Language  Developers and Business People  move in different worlds  have different languages to express their ideas  the other 10th kind of people how do not know about binary…  use company- or industry-standard terminology Domain Driven Design
  13. 13. Ubiquitous Language  Developers and Business People Domain Driven Design
  14. 14. Ubiquitous Language  Language should be Ubiquitous  In classes, methods, variables, even in tests  Behavior-Driven Development  Conversing using the same language  ‘Solution smells’ detected by Domain Experts  Discovery of new domain concepts by developers  Shared learning by all involved  Model must evolve: always remove ambiguities Domain Driven Design
  15. 15. Ubiquitous Language  The best of both worlds Domain Driven Design
  16. 16. Domain Driven Design Domain Driven Design Model-Driven Design Ubiquitous Language define model with Bounded Contexts identify scope with Services process model with Entities express model with Value Objects express model with Clean/Layered/ Hexagonal Architecture isolate domain with Events express state changes with RAD exclude Repositories access with Aggregates encapsulate with Factories instantiated by encapsulate with instantiated by access with instantiated by
  17. 17. Modeling a Domain  What do we call Domain here?  The domain represents a sphere of knowledge, influence or activity  As a result  The domain has to be clearly identified  Your software is expected to solve a set of problems related to this domain  You may have several domains to modelize Domain Driven Design
  18. 18. Modeling  DDD is some case of Model-Driven Design  Its purpose is to create a model of a given domain  The code itself will express the model: as a consequence, any code refactoring means changing the model, and vice-versa Domain Driven Design
  19. 19. Modeling  Be honest: reality is just too big  Modeling is about filtering the reality for a given use context  “All models are wrong, some are useful” G. Box, statistician  Several models may coexist for a given reality, depending of the knowledge level involved  what we call a Bounded Context Domain Driven Design
  20. 20. Modeling  Bounded Context  Organize your code between bounded contexts  Most objects and services will be specific to each context, tuned to each model  Some objects (or parents) may be reused in the same domain (but not between domains)  Ubiquitous language applied  Consistent naming between the contexts  Proper namespace / units use  Domains and Contexts appear in source code folders Domain Driven Design
  21. 21. Modeling  Bounded Context  The same reality will appear several times in several models  Don't be afraid if the same reality is defined several times in your domain code, one class for each context  Always specify your current modelization context  Just as in Google Maps the zoom level or the kind of map shows several models of the same world Domain Driven Design
  22. 22. Modeling  Modeling is about forgetting the details  Focus on the essentials  Given an objective knowledge level  Specific to a bounded context Domain Driven Design
  23. 23. Modeling  Model State  Static  To abstract a given state of the reality  Dynamic  To abstract how reality evolves (i.e. its behavior)  Changes are mostly continuous in reality  Dynamic modeling will create static snapshots of the reality (called state transitions)  It will embrace the deterministic nature of computers Domain Driven Design
  24. 24. Modeling  State brings complexity  It is a fact we won’t argue  So our code should be as stateless as possible  Some patterns  Try to always separate value and time in state  Reduce statefulness to only the necessary  Implement your logic as state machines  instead of blocking code or sessions  Persistence should handle one-way transactions Domain Driven Design
  25. 25. Modeling  DDD expresses static model state using  Immutable Value Objects  To define a static value  Entity Objects (or Entities)  To refer to a given state of given identity  For instance, the same identity (named "John Doe") may be, at a given state, single and minor, then, at another state, married and adult. The model will help to express the given states, and the state transitions between them (e.g. John's marriage) Domain Driven Design
  26. 26. Modeling  DDD expresses dynamic model state  Via Factory / Repository / Unit Of Work patterns  Code will get given state of the model  Then process its domain knowledge  And return the new state  Via Events  When a system does change its state very often  Events may be the core of the domain  See Event-Driven Design or Event Sourcing Domain Driven Design
  27. 27. Modeling  To express the modularity of the model  Partitioning  the more your elements have a separated concern, the better, since the model will be more stateless  we will create a lot of objects (interface segregation)  not abuse of inheritance  are you focusing on the domain, or on your code?  Grouping  to express constraints, elements may be grouped  usually, no more than 6/8 elements per diagram  Aggregate Root to group objects to model constraints Domain Driven Design
  28. 28. Domain Driven Design Domain Driven Design Model-Driven Design Ubiquitous Language define model with Bounded Contexts identify scope with Services process model with Entities express model with Value Objects express model with Clean/Layered/ Hexagonal Architecture isolate domain with Events express state changes with RAD exclude Repositories access with Aggregates encapsulate with Factories instantiated by encapsulate with instantiated by access with instantiated by
  29. 29. Value Objects and Entities  Model-level structures  Reduce the model into objects or structured types  May be class or record  Make the implicit explicit  Naming should follow the Ubiquitous language  Define dedicated types  e.g. a TPhoneNumber instead of plain string/RawUTF8  Use dynamic structures like TDocVariant  Especially during initial exploring phase  Or to pass opaque infrastructure information Domain Driven Design
  30. 30. Value Objects and Entities  Model-level representation will define  Value Objects contain attributes (value, size) but no conceptual identity  e.g. money bills, or seats in a Rock concert  Entity objects are not defined by their attributes (values), but their thread of continuity, signified by an identity  e.g. persons, or seats in most planes, as each one is unique and identified. Domain Driven Design
  31. 31. Value Objects and Entities  Value objects are immutable by definition  So should be handled as read-only  They are incapable of change once they are created  Seeking side-effect-free functions  concept borrowed by DDD to functional languages Domain Driven Design
  32. 32. Value Objects and Entities  Entities will very likely have an ID field  To identify a given reality  To model the thread of continuity of this identity  But this ID is an implementation detail  Only used at Persistence Layer level  At Domain Layer level, data access via an Aggregate Root, linked to a bounded context  May be hidden by CQRS statefull services Query an aggregate, then apply Commands Domain Driven Design
  33. 33. Value Objects and Entities  Aggregates are a particular case of Entities  Defined as collection of objects  nested Values and/or Entities  That are grouped together by a root Entity otherwise known as an Aggregate Root  which scope has been defined by execution context  Allow composition (or grouping) in the model  For persistence, are the transactional boundary  May be NoSQL, or at least via ORM Domain Driven Design
  34. 34. DTO & Events  Isolate the domain from the outer world  Value Objects may be used with no translation  So may be used as DTO classes  Even Entities may be transmitted directly  Since their methods should not refer to anything but their internal properties  In short: be realistic/lazy, but paranoid  Better isolate your domain with DTO types  To increase maintainability and efficiency Domain Driven Design
  35. 35. DTO & Events  Data Transfer Objects (DTO)  are transmission objects  to avoid leaking the Domain objects across the wire  Anti-Corruption Layer i.e. separate your layers  Create gatekeepers that to prevent non-domain concepts from leaking into your model  Even public API should use adapters Domain Driven Design
  36. 36. DTO & Events  Commands and Events  are some kind of DTO  since they communicate data about an event and they themselves encapsulate no behavior  in mORMot, interface types e.g. over Websockets or via master/slave replication of simple tables Domain Driven Design
  37. 37. Factory & Repository  Factory pattern  is used to create class instances  In strongly-typed OOP (like in Delphi, Java or C#), this pattern is in fact its constructor method and associated class type definition, which will define a fixed set of properties and methods at compilation  not as e.g. in JavaScript or most other script languages  is used to create interface instances  see SOLID principles (mainly Liskov substitution) Domain Driven Design
  38. 38. Factory & Repository  Repository pattern  used to save and dispense each Aggregate Root  Can use e.g. TSQLRecord “Layer Supertype”  ORM / CRUD interface  Or dedicated repository classes  Dedicated interfaces (may be CQRS but not anemic)  Following Ubiquitous domain language (not CRUD pattern)  Saving data is a concern orthogonal to the model  DDD architects claim that persistence is infrastructure, not domain  Domain layer should be abstracted (via IoC) Domain Driven Design
  39. 39. Domain Driven Design Domain Driven Design Model-Driven Design Ubiquitous Language define model with Bounded Contexts identify scope with Services process model with Entities express model with Value Objects express model with Clean/Layered/ Hexagonal Architecture isolate domain with Events express state changes with RAD exclude Repositories access with Aggregates encapsulate with Factories instantiated by encapsulate with instantiated by access with instantiated by
  40. 40. Services  Aggregate roots’ methods  Aggregate roots are the only kind of entities to which your software may hold a reference  Tend to be the main access point of any process  from the application layer point of view  Often end up as state machines  with all their methods  It could be handy to publish those methods as stateless Services isolated at Application layer level Domain Driven Design
  41. 41. Services  Domain services  are used to model primary operations  i.e. publish tools for modeling processes  that do not have an identity or life-cycle in your domain  that is, that are not linked to one particular aggregate root, perhaps none, or several  In this terminology, services are not tied to a particular person, place, or thing in the application, but tend to embody processes  Main rule is to let the Domain layer focus on the business logic Domain Driven Design
  42. 42. Services  Domain services  Named after verbs or business activities  That domain experts introduce into Ubiquitous Language  Should be exposed as client-oriented methods  Following Interface segregation principle  As a reusable toolbox: do not leak your domain!  Application layer services  Would use the Domain Services  To implement the needs of client applications Domain Driven Design
  43. 43. Services  Unit Of Work  Can be used to maintain a list of objects affected by a business transaction  Coordinates the writing out of changes and the resolution of concurrency problems  Persistence Ignorance or Database agnosticism  At application layer level  Implements transactions for Domain entities and services  May be implemented by ORM to “hydrate” Aggregate roots class instances as abstractly as possible Domain Driven Design
  44. 44. Domain Driven Design Domain Driven Design Model-Driven Design Ubiquitous Language define model with Bounded Contexts identify scope with Services process model with Entities express model with Value Objects express model with Clean/Layered/ Hexagonal Architecture isolate domain with Events express state changes with RAD exclude Repositories access with Aggregates encapsulate with Factories instantiated by encapsulate with instantiated by access with instantiated by
  45. 45. Clean / Layered Architecture Domain Driven Design  DDD 4-tier layered architecture  Presentation Layer  Application Layer  Domain Layer  Business Layer  and cross-cutting / vertical layer  With proper isolation of the Domain layer  To focus on the domain  To not let the domain be polluted  by technical stuff, application particularities…
  46. 46. DDD n-Tier Architecture Domain Driven Design
  47. 47. Clean DDD architecture  From the physical point of view  N-layered DDD architecture Domain Driven Design Layer Description Presentation MVC UI generation and reporting Application Services and high-level adapters Domain Model Where business logic remains Data persistence ORM and external services Cross-Cutting Horizontal aspects shared by other layers
  48. 48. Clean DDD architecture  From the physical point of view  Still looks like a classic 4-tier layered design  But DDD does its best to isolate the Domain Model from any dependency  Abstract from technical details  Do not be tied to the application layer  To modelize a “clean” architecture Domain Driven Design
  49. 49. Domain Driven Design Technical Implementations Application Services Domain Services Domain Model Unit Tests Aggregates Value Objects Entities Third Party Interfaces Repository Interfaces Domain Interfaces Workflows execute get/save objects use objects Behavior Tests validate Infrastructure implements User Interface exposes DB ORM File System Web Services Mocks Stubs Fake Datasets Rich Client Web AJAX
  50. 50. Clean DDD architecture  From the logical point view  Onion-like more than layered-like  Domain at the core  Should stay as stable as possible  Stay as uncoupled as possible  Define domain objects  Value Objects, Entities, Aggregate Roots  Define domain services consumed outside  Define abstract services implemented outside  e.g. persistence interface Domain Driven Design
  51. 51. Clean DDD architecture  From the logical point view  Onion-like more than layered-like  Application services layer  Will change very often and evolve a lot  Typical workflow:  Dehydrate Aggregate Roots using persistence service  Call the Domain services  Call external services, commit persistence (Unit of work) Domain Driven Design
  52. 52. Clean DDD architecture  From the logical point view  Onion-like more than layered-like  Presentation services layer  For each end-user application  Depending on each technology (VCL, HTML, AJAX)  Infrastructure services layer  Persistence depending on database (SQL/NoSQL)  External services (SOA)  Tests with stubs and mocks  Regression and integration tests are part of the design Domain Driven Design
  53. 53. Clean DDD architecture  Clean, since it controls coupling  Coupling is toward the center  All code can depend on layers more central  But cannot depend on layers further out from the core  This architecture is unashamedly biased toward OOP, which puts objects before all others  Relies on the Dependency Inversion principle  Uses interface for behavior contract  Force the externalization of infrastructure Domain Driven Design
  54. 54. Clean DDD architecture  Clean, since it is upside-down  Database is not the center of your logic  Nor the bottom of your physical design  Database is external  There is no such “database application” in DDD  As any other third-party service  Favor isolation between layers  Via dedicated adaptor services Domain Driven Design
  55. 55. Domain Driven Design Technical Implementations Application Services Domain Services Domain Model Unit Tests Aggregates Value Objects Entities Third Party Interfaces Repository Interfaces Domain Interfaces Workflows execute get/save objects use objects Behavior Tests validate Infrastructure implements User Interface exposes DB ORM File System Web Services Mocks Stubs Fake Datasets Rich Client Web AJAX
  56. 56. DDD commitments  I shall collaborate with domain experts  I shall focus on using our ubiquitous language  I shall not care about technical stuff or framework, but about modeling the Domain  I shall make the implicit explicit  I shall use end-user scenarios to get real and concrete  I shall not be afraid of defining one model per context  I shall focus on my Core Domain  I shall let my Domain code be uncoupled from any external influence  I shall separate values and time in state  I shall reduce statefulness to only the necessary  I shall always adapt my model as soon as possible, once it appears inadequate Domain Driven Design
  57. 57. DDD & mORMot Domain Driven Design
  58. 58. DDD & mORMot  DDD may be implemented with mORMot  Value objects  as record and dynamic arrays  or TSynPersistent / TSynAutoCreateField class  Entities (and Aggregate Roots)  as TSynAutoCreateField class and mORMotDDD.pas TDDDRepositoryRestFactory  or directly – but not preferred – as TSQLRecord  Data Transfer Objects as record or TDocVariant  Depending if the schema is fixed or variable Domain Driven Design
  59. 59. DDD & mORMot  DDD may be implemented with mORMot  Services as interface-based services  At Domain or Application layer  To be accessed locally or remotely  Security, Asynchronous Callbacks (Websockets)  Services as method-based services  At Domain layer, for Aggregate root methods  At Application layer, for publishing REST services Domain Driven Design
  60. 60. DDD & mORMot  DDD may be implemented with mORMot  Persistence as TSQLRest or dedicated service  With TSQLRestBatch as Unit-Of-Work  Advanced mapping via mORMotDDD.pas TDDDRepositoryRestFactory  Command Query Segregation Services (CQRS)  mORMotDDD.pas ICQRSQuery ICQRSCommand  Dual-phase commit for SOA orchestration Domain Driven Design
  61. 61. DDD & mORMot  DDD may be implemented with mORMot  Desktop Applications User Interface  With optional auto-generation of the layout  Including grids, i18n and interaction with the VCL  Web Applications User Interface  AJAX over REST/SOA  Web using MVC/Mustache  Code-driven reporting  Data from ORM/SOA objects, not TDataSet  Integrated preview and PDF export Domain Driven Design
  62. 62. DDD & mORMot  DDD may be implemented with mORMot  Services/daemons abstract classes  Thread-based or process-based daemons  Integration as Windows Services or Linux Daemons  Settings, console, monitoring, remote administration  All cross-cutting features are available  Filtering/validating, security, cache, logging  JSON, transmission, RTTI, tests, stubs/mocks Domain Driven Design
  63. 63. Domain Driven Design Presentation Application Data persistence Domain Model Cross-Cutting AJAX REST Client REST Server HTTP 1.1 Cache UI i18n Filtering Validation Reporting ORM Services (interface-based) Security Sessions SQLite3 External DB Value Objects as record Entities as TSQLRecord Aggregates as TSQLRecord Tests Mocks/Stubs Logging
  64. 64. Domain Driven Design Arnaud Bouchez

×