Successfully reported this slideshow.
Your SlideShare is downloading. ×

Implementing Domain-Driven Design study group - ch. 5 entities

Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad

Check these out next

1 of 48 Ad

More Related Content

Similar to Implementing Domain-Driven Design study group - ch. 5 entities (20)

Advertisement

Recently uploaded (20)

Implementing Domain-Driven Design study group - ch. 5 entities

  1. 1. © 2019, Domain Driven Design Taiwan Community DDD Reading Club Sharing Ch. 5 Entities Henry Tong May 29, 2019 Source: Ch. 5 of Implementing Domain-Driven Design, Vaughn Vernon
  2. 2. © 2019, Domain Driven Design Taiwan Community Outlines 1.Why entities? - definitions and motivations 2.Designing entities • Unique identity • Discover entities • Essential behavior • Roles and responsibilities • Construction • Validation • Change Tracking
  3. 3. © 2019, Domain Driven Design Taiwan Community Source: Domain-Driven Design Reference by Evans
  4. 4. © 2019, Domain Driven Design Taiwan Community Definition of entities (from Evans) • Notice its identity, rather than its attributes • When an object is distinguished by its identity, rather than its attributes, make this primary to its definition in the model. • Uniqueness • Define a means of distinguishing each object regardless of its form or history • Define an operation that is guaranteed to produce a unique result for each object • The model must define what it means to be the same thing
  5. 5. © 2019, Domain Driven Design Taiwan Community Definition of entities - cont. • The entity may change • Represent a thread of identity that runs through time and often across distinct representations • Not just attributes • An object must be distinguished from other objects even though they might have the same attributes • E.g. Two bank accounts both have balance NTD $583,794. Question: Are they the same account? – No. Account balance is attribute. We care about the identity of the account
  6. 6. © 2019, Domain Driven Design Taiwan Community Key motivation for entities • Differentiation between entities (ch. 5) vs value objects (ch. 6) • We want to trace the unique identity and mutability (changing) characteristics of entities • If the domain concept doesn't fit entities’ definition, then it's a value object • To be covered in chapter 6 • Remember the motivation for DDD • For simple system - Just CRUD may be enough • But, if business evolves, CRUD is not enough to model complex business relationship
  7. 7. © 2019, Domain Driven Design Taiwan Community Outlines 1.Why entities? - definitions and motivations 2.Designing entities • Unique identity • Discover entities • Essential behavior • Roles and responsibilities • Construction • Validation • Change Tracking
  8. 8. © 2019, Domain Driven Design Taiwan Community Unique identity for entities • Focus on attributes and behaviors for • Identifying and matching • Querying and searching • Notes: A search function may use name as keywords – But the name normally is NOT the identifier – A person’s name is normally not unique, needs a unique ID attribute
  9. 9. © 2019, Domain Driven Design Taiwan Community Four identity creation strategy 1.The user provides one or more original unique values 2.The application internally generates an identity 3.The application relies on a persistence store to generate a unique identity. 4.Another Bounded Context (2) (system or application) has already determined the unique identity
  10. 10. © 2019, Domain Driven Design Taiwan Community Four identity creation strategy - 1 • Main issue – User may key it “uncorrectly” -> then need to provide method to change ID • Suggestion: Store user-entered values as entity properties, but not as unique identity (if possible!) 1.The user provides one or more original unique values as input to the application. The application must ensure that they are unique
  11. 11. © 2019, Domain Driven Design Taiwan Community Four identity creation strategy - 2 2. The application internally generates an identity using an algorithm that ensures uniqueness. We can get a library or framework to do this for us, but it can be done by the application. • E.g. Follow the below 4 steps and concatenate to a 128-bit unique val. • 1. Time in milliseconds on the computing node • 2. IP address of the computing code • 3. Object identity of the factory object instance within the virtual machine (Java) • 4. Random number generated by the same generator within the virtual machine (Java) • Example Result: f36ab21c-67dc-5274-c642-1de2f4d5e72a • Or use a UUID generator such as below for Java: • String rawId = java.util.UUID.randomUUID().toString();
  12. 12. © 2019, Domain Driven Design Taiwan Community Four identity creation strategy - 3 3. The application relies on a persistence store, such as a database, to generate a unique identity. • E.g., use Oracle’s sequence number generation feature: CREATE SEQUENCE supplier_seq MINVALUE 1 START WITH 1 INCREMENT BY 1 CACHE 20; INSERT INTO suppliers (supplier_id, supplier_name) VALUES (supplier_seq.NEXTVAL, 'Kraft Foods'); • Note: Beware of performance issues. It can take significantly longer to go to the database to get each value than to generate identities in the application • OK if the model can suffice with late identity generation Example link: https://www.techonthenet.com/oracle/sequences.php
  13. 13. © 2019, Domain Driven Design Taiwan Community Four identity creation strategy - 4 4. Another Bounded Context (2) (system or application) has already determined the unique identity. It is input or selected by the user from a set of choices. • Provide a search screen for users to search for the external entity • Synchronization implications • External changes may affect our local entitiy • Can subscribe to domain events to receive the changes • Most complex of the 4 strategies – only use if necessary (conservatively)
  14. 14. © 2019, Domain Driven Design Taiwan Community Identity creation - In-depth issues • Timing - when to create identity • Sometimes, we don’t care, let repository (persistence store) to create • But sometimes, if we need to generate an event on creation, we need to get the identity back to complete the creation • Surrogate identity • Only used by implementation technology, like ORM (Hibernate) (the “outside” of hexagonal architecture in ch. 4) • No relationship with domain model • Can use a “Layer Supertype” (Fowler) to hide it • Put in an abstract base class “above” our entities class – E.g. java.lang.Object • Identity stability - ID cannot be changed! • Hide identity setters from clients • Create guards in setters to prevent changes • if (this.username != null) { throw exception; }
  15. 15. © 2019, Domain Driven Design Taiwan Community Outlines 1.Why entities? - definitions and motivations 2.Designing entities • Unique identity • Discover entities • Essential behavior • Roles and responsibilities • Construction • Validation • Change Tracking
  16. 16. © 2019, Domain Driven Design Taiwan Community SaaSOvation case study • Develop software as a service (SaaS) products: • CollabOvation: collaboration tools: • Forums, shared calendars, blogs, instant messaging, wiki, message boards, document management, announcements, alerts, … • ProjectOvation: management of agile projects: • Scrum mgmt: product, product owner, team, backlog items, planned releases, sprints, … •See figure 3.5 for context map
  17. 17. © 2019, Domain Driven Design Taiwan Community SaaSOvation case study - cont. • IAM Context (see figure 2.9) • Support for multi-tenant subscribers. • Each tenant and every object asset owned by a given tenant would have a completely unique identity • Logically isolating each tenant from all others. Users of the systems are registered via self- service by invitation only.
  18. 18. © 2019, Domain Driven Design Taiwan Community Software requirements for SaaSOvation project • Users exist in association with and under the control of a tenancy. • Users of a system must be authenticated. • Users possess personal information, including a name and contact information. • User personal information may be changed by the users themselves or by a manager. • User security credentials (passwords) may be changed. • Tenants allow for the registration of many users by invitation. • Tenants may be active or be deactivated. • Users of a system must be authenticated but can be authenticated only if the tenant is active. • . . . Scope: Identity and Access Context Pay attention! We will be using these requirements to study entity design!!!
  19. 19. © 2019, Domain Driven Design Taiwan Community Analysis - Discover entities • Change keyword: user info may be changed • Authenticated keyword: user may need to be searched and authenticated for a tenant • Both users and tenants need to be uniquely identified • Resolution: User and Tenant are entities • Users exist in association with and under the control of a tenancy. • Users of a system must be authenticated. • User personal information may be changed by the users themselves or by a manager. • User security credentials (passwords) may be changed. • Tenants allow for the registration of many users by invitation. • . . .
  20. 20. © 2019, Domain Driven Design Taiwan Community Analysis - Essential attributes - Unique identifier • Tenant • Use UUID as unique identifier • String or “strong” type for the ID? • The ID will be set on all other entities in every Context • Chose “Strong” typing - Define a TenantID value object • User • Unique username, and an encrypted password • Should the password be part of the ID as a value object? • No. Since password may be changed
  21. 21. © 2019, Domain Driven Design Taiwan Community Outlines 1.Why entities? - definitions and motivations 2.Designing entities • Unique identity • Discover entities • Essential behavior • Roles and responsibilities • Construction • Validation • Change Tracking
  22. 22. © 2019, Domain Driven Design Taiwan Community Tenant behavior • Authentication - not just matching ID and password • Better to add: AuthenticationService • SetActive(flag) enough? Using a boolean flag? • Understand domain user intention • Or: to understand the semantics 語意 • Better: add operations in Tenant: Activate(), Deactivate(), IsActive() • User registration: add registerUser() operation in Tenant • Users of a system must be authenticated but can be authenticated only if the tenant is active. • Tenants allow for the registration of many users by invitation. • Tenants may be active or be deactivated.
  23. 23. © 2019, Domain Driven Design Taiwan Community User behavior • Personal info is needed • Add Person class - do not put too much responsibility on User • Is Person an entity? • Notice keyword “changed” for personal info • If modeled as value object, we replace the entire Person object any time there is a change, e.g. phone # change • Decision: Model Person as an entity • Users possess personal information, including a name and contact information. • User personal information may be changed by the users themselves or by a manager. • User security credentials (passwords) may be changed. • User password change • Add changePassword() operation in User • User always = Person? • Can user be an external system? • Decision: No such requirement now. Do not over design • Model basic personal name and contact change in User • Future: Provide Principal interface, and Person and System would each be a specialized Principal
  24. 24. © 2019, Domain Driven Design Taiwan Community User behavior:
  25. 25. © 2019, Domain Driven Design Taiwan Community Outlines 1.Why entities? - definitions and motivations 2.Designing entities • Unique identity • Discover entities • Essential behavior • Roles and responsibilities • Construction • Validation • Change Tracking
  26. 26. © 2019, Domain Driven Design Taiwan Community Roles and Responsibilities • In OO, generally interfaces determine the roles of an implementing class. When designed correctly, a class has one role for each interface that it implements. • E.g., • Class User in the preceding examples implements no explicit interfaces, yet it plays one role, a User.
  27. 27. © 2019, Domain Driven Design Taiwan Community Roles and Responsibilities • Simple solution: • Model the operations in Customer entity: • Add new orders to a customer. • Make a customer preferred (the condition for meeting this level is not stated)
  28. 28. © 2019, Domain Driven Design Taiwan Community Roles and Responsibilities • Another solution: • Implement two fine-grained role interfaces: • Other use-case-specific behavior can be associated with any given role, such as validation
  29. 29. © 2019, Domain Driven Design Taiwan Community Roles and Responsibilities • No right answer about the previous 2 designs • Leverage interfaces to hide implementation details that we don’t want leaking out of the model to clients. • Design an interface to expose exactly what we want to allow clients to use, and nothing more. • Beware of: • Object schizophrenia (object identity confusion) - see ch. 5 • Also note: “Interface Segregation Principle” in SOLID patterns from Uncle Bob (Robert Martin) • Avoid "fat" interfaces, design cohesive set of methods
  30. 30. © 2019, Domain Driven Design Taiwan Community Outlines 1.Why entities? - definitions and motivations 2.Designing entities • Unique identity • Discover entities • Essential behavior • Roles and responsibilities • Construction • Validation • Change Tracking (suggest to publish domain events to track important changes)
  31. 31. © 2019, Domain Driven Design Taiwan Community Entity construction • An entity maintains one or more invariant from construction • Invariant - a state that must stay transactionally consistent throughout the Entity life cycle. Any example that we can think of? • E.g. user password cannot be null, a car has 4 wheels, max 10 line items per order • Check the invariant rules during construction • Normally, Aggregates care about invariants, but since aggregate roots are entities, it’s covered here • Use a Factory for complex Entity instantiations • E.g. the method registerUser() is the Factory • Note: Factory Method Pattern
  32. 32. © 2019, Domain Driven Design Taiwan Community Entity validation • Validation - check the correctness of 1. any one attribute/property, 2. any whole object, 3. any composition of objects. • Notice the 3 levels of validation • Just because all of the attributes/properties of a domain object are individually valid, that does not mean that the object as a whole is valid • Maybe the combination of two correct attributes invalidates the whole object • Just because a single object as a whole is valid, that does not mean that a composition of objects is valid. • Perhaps the combination of two Entities, each of which has individual valid states, actually makes the composition invalid
  33. 33. © 2019, Domain Driven Design Taiwan Community Validating an attribute/property - 1 • Design by Contract • E.g. setEmailAddress() • Specify preconditions, postconditions, variants to check, e.g. • The parameter may not be null. • The parameter must not be an empty string. • The parameter must be 100 characters in length or less (but not zero characters). • The parameter must match the basic format of an e-mail address. • Above is Defensive programming • Question: Shall we check for empty string, string length? • Some engineers check for empty string, but leave size check to DB • Author: suggest to check as much as possible. Handling exceptions may be tricky
  34. 34. © 2019, Domain Driven Design Taiwan Community Validating Whole Objects (all properties!) - 2 • Definition • Even though we may have an Entity with completely valid attributes/ properties, it does not necessarily mean the entire Entity is valid. To validate a whole Entity, we need to have access to the state of the entire object—all of its attributes/properties. • Deferred Validation - “a class of checking that should be deferred until the last possible moment.” • Suggest to have a separate validation component • Validation rules of a domain object often changes more often than the domain object itself. Embedding validation inside an Entity also gives it too many responsibilities. • Define validation algorithm with Strategy/Specification pattern • Define notification handler to handle “invalid” condition!
  35. 35. © 2019, Domain Driven Design Taiwan Community Validating Object Compositions - 3 • Validate that a cluster or composition of Entities are all valid together, including one or more Aggregate instances • Again, use Deferred Validation • Suggestion: • Use a Domain Service. The Domain Service can use Repositories to read the Aggregate instances it needs to validate • When the conditions are ready for validation, the model could inform clients by publishing a Domain Event
  36. 36. © 2019, Domain Driven Design Taiwan Community Workshop • Background • A company provides IT Body Leasing (接案). They have some Employees, and also a lot of Freelancers as Subcontractors. Currently, they use Excel sheets to manage their Customers, Freelancers, Timesheets and so on. • New goal: to build a new web based solution with role based security • Requirement summary • A searchable catalog of Freelancer must be provided • The new solution must allow to store the different Communication Channels (e.g. email, fax, mobile) available to contact a Freelancer • A searchable catalog of Projects must be provided • A searchable catalog of Customers must be provided • The Timesheets for the Freelancers under contract must be maintained
  37. 37. © 2019, Domain Driven Design Taiwan Community Workshop - cont. • Example usage scenarios • Freelancer moved to new location address • A Customer can only be deleted if there is no Project assigned • Once a Timesheet is entered, the Customer needs to be billed • Work shop tasks • Identify the entries and non-entities in the requirements • List the attributes and operations of the entities
  38. 38. © 2019, Domain Driven Design Taiwan Community Let’s divide into team to work out the model! • A searchable catalog of Freelancer must be provided • The new solution must allow to store the different Communication Channels (e.g. email, fax, mobile) available to contact a Freelancer • A searchable catalog of Projects must be provided • A searchable catalog of Customers must be provided • The Timesheets for the Freelancers under contract must be maintained • Freelancer moved to new location address • A Customer can only be deleted if there is no Project assigned • Once a Timesheet is entered, the Customer needs to be billed • Identity and Access Management Subdomain • Freelancer Management Subdomain • Customer Management Subdomain • Project Management Subdomain • Work shop tasks • Identify the entities and non-entities in the requirements • List the attributes and operations of the entities Key Entity Characteristics: • Unique identity • Not just attributes • We care about the changes
  39. 39. © 2019, Domain Driven Design Taiwan Community Workshop Source and Overview of example project • Source URL: • https://www.mirkosertic.de/blog/2013/04/domain-driven-design-example/ • An example project to illustrate Domain Driven Design Principles • Freelancer moved to new location address • A Customer can only be deleted if there is no Project assigned • Once a Timesheet is entered, the Customer needs to be billed • DDD output examples • Domain Model (entities and main attributes) • Design for the 3 usage scenarios (add operations)
  40. 40. © 2019, Domain Driven Design Taiwan Community Workshop example project: Domain model
  41. 41. © 2019, Domain Driven Design Taiwan Community • Notice “address” related operations added for Freelancer • Freelancer moved to new location address
  42. 42. © 2019, Domain Driven Design Taiwan Community • A “Synchronous integration” scenario • Integrate between Customer management and Project management contexts • Customer management context: • deleteCustomerByid operation -> also need to check if a project exist in project management context • A Customer can only be deleted if there is no Project assigned
  43. 43. © 2019, Domain Driven Design Taiwan Community • Project management context: • Implementation of “projectExistFor()” operation • Will be called by customer management context • A Customer can only be deleted if there is no Project assigned
  44. 44. © 2019, Domain Driven Design Taiwan Community • An “Asynchronous integration” scenario: • Customer management context waits for “timesheet entered” event to happen from Freelancer management context, then start billing • Freelancer management context: • After timesheet is entered, will store an event • Utilize a “JMS” (Java message service) adapter to notify subscribers (customer management context) • Once a Timesheet is entered, the Customer needs to be billed
  45. 45. © 2019, Domain Driven Design Taiwan Community • Customer management context: • JMS message receiver will receive the “timesheet entered” event • It will call a “timesheetEntered” handler to complete the subsequent billing activities • Once a Timesheet is entered, the Customer needs to be billed
  46. 46. © 2019, Domain Driven Design Taiwan Community Summary • Remember • We care about the unique identity and mutability (changing) characteristics of entities • The four primary ways to generate Entity unique identities • How to discover the entities, and their properties and operations from the requirements (uncovering the ubiquitous language) • Define entity roles with interfaces • Entity construction, and validation suggestions
  47. 47. © 2019, Domain Driven Design Taiwan Community Additional References 1.Evans, E.: Domain-driven design : tackling complexity in the heart of software 2.Evans, E.: Domain-Driven Design Reference
  48. 48. © 2019, Domain Driven Design Taiwan Community Q & A

×