SlideShare una empresa de Scribd logo
1 de 48
Descargar para leer sin conexión
© 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
© 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
© 2019, Domain Driven Design Taiwan Community Source: Domain-Driven
Design Reference by Evans
© 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
© 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
© 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
© 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
© 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
© 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
© 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
© 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();
© 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
© 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)
© 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; }
© 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
© 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
© 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.
© 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!!!
© 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.
• . . .
© 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
© 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
© 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.
© 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
© 2019, Domain Driven Design Taiwan Community
User behavior:
© 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
© 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.
© 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)
© 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
© 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
© 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)
© 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
© 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
© 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
© 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!
© 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
© 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
© 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
© 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
© 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)
© 2019, Domain Driven Design Taiwan Community
Workshop
example
project:
Domain model
© 2019, Domain Driven Design Taiwan Community
• Notice “address”
related operations
added for Freelancer
• Freelancer moved to new
location address
© 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
© 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
© 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
© 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
© 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
© 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
© 2019, Domain Driven Design Taiwan Community
Q & A

Más contenido relacionado

La actualidad más candente

Domain driven design
Domain driven designDomain driven design
Domain driven designits_skm
 
Azure SQL Database & Azure SQL Data Warehouse
Azure SQL Database & Azure SQL Data WarehouseAzure SQL Database & Azure SQL Data Warehouse
Azure SQL Database & Azure SQL Data WarehouseMohamed Tawfik
 
Easy Microservices with JHipster - Devoxx BE 2017
Easy Microservices with JHipster - Devoxx BE 2017Easy Microservices with JHipster - Devoxx BE 2017
Easy Microservices with JHipster - Devoxx BE 2017Deepu K Sasidharan
 
Databricks for Dummies
Databricks for DummiesDatabricks for Dummies
Databricks for DummiesRodney Joyce
 
Introduction to microservices
Introduction to microservicesIntroduction to microservices
Introduction to microservicesAnil Allewar
 
From Monolithic to Microservices
From Monolithic to Microservices From Monolithic to Microservices
From Monolithic to Microservices Amazon Web Services
 
Prometheus
PrometheusPrometheus
Prometheuswyukawa
 
NoSQL databases - An introduction
NoSQL databases - An introductionNoSQL databases - An introduction
NoSQL databases - An introductionPooyan Mehrparvar
 
AWS vs Azure vs Google (GCP) - Slides
AWS vs Azure vs Google (GCP) - SlidesAWS vs Azure vs Google (GCP) - Slides
AWS vs Azure vs Google (GCP) - SlidesTobyWilman
 
Microservices, Containers, Kubernetes, Kafka, Kanban
Microservices, Containers, Kubernetes, Kafka, KanbanMicroservices, Containers, Kubernetes, Kafka, Kanban
Microservices, Containers, Kubernetes, Kafka, KanbanAraf Karsh Hamid
 
Introduction to Azure Databricks
Introduction to Azure DatabricksIntroduction to Azure Databricks
Introduction to Azure DatabricksJames Serra
 
Cloud Storage in Azure, AWS and Google Cloud
Cloud  Storage in Azure, AWS and Google CloudCloud  Storage in Azure, AWS and Google Cloud
Cloud Storage in Azure, AWS and Google CloudThurupathan Vijayakumar
 
Azure architecture
Azure architectureAzure architecture
Azure architectureAmal Dev
 
Design patterns for microservice architecture
Design patterns for microservice architectureDesign patterns for microservice architecture
Design patterns for microservice architectureThe Software House
 
Introduction To Microservices
Introduction To MicroservicesIntroduction To Microservices
Introduction To MicroservicesLalit Kale
 
Microservice vs. Monolithic Architecture
Microservice vs. Monolithic ArchitectureMicroservice vs. Monolithic Architecture
Microservice vs. Monolithic ArchitecturePaul Mooney
 

La actualidad más candente (20)

Domain driven design
Domain driven designDomain driven design
Domain driven design
 
Azure SQL Database & Azure SQL Data Warehouse
Azure SQL Database & Azure SQL Data WarehouseAzure SQL Database & Azure SQL Data Warehouse
Azure SQL Database & Azure SQL Data Warehouse
 
Easy Microservices with JHipster - Devoxx BE 2017
Easy Microservices with JHipster - Devoxx BE 2017Easy Microservices with JHipster - Devoxx BE 2017
Easy Microservices with JHipster - Devoxx BE 2017
 
Databricks for Dummies
Databricks for DummiesDatabricks for Dummies
Databricks for Dummies
 
Introduction to microservices
Introduction to microservicesIntroduction to microservices
Introduction to microservices
 
Event Storming and Saga
Event Storming and SagaEvent Storming and Saga
Event Storming and Saga
 
From Monolithic to Microservices
From Monolithic to Microservices From Monolithic to Microservices
From Monolithic to Microservices
 
Prometheus
PrometheusPrometheus
Prometheus
 
NoSQL databases - An introduction
NoSQL databases - An introductionNoSQL databases - An introduction
NoSQL databases - An introduction
 
AWS vs Azure vs Google (GCP) - Slides
AWS vs Azure vs Google (GCP) - SlidesAWS vs Azure vs Google (GCP) - Slides
AWS vs Azure vs Google (GCP) - Slides
 
Microservices, Containers, Kubernetes, Kafka, Kanban
Microservices, Containers, Kubernetes, Kafka, KanbanMicroservices, Containers, Kubernetes, Kafka, Kanban
Microservices, Containers, Kubernetes, Kafka, Kanban
 
An intro to Azure Data Lake
An intro to Azure Data LakeAn intro to Azure Data Lake
An intro to Azure Data Lake
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
 
Introduction to Azure Databricks
Introduction to Azure DatabricksIntroduction to Azure Databricks
Introduction to Azure Databricks
 
Cloud Storage in Azure, AWS and Google Cloud
Cloud  Storage in Azure, AWS and Google CloudCloud  Storage in Azure, AWS and Google Cloud
Cloud Storage in Azure, AWS and Google Cloud
 
Azure architecture
Azure architectureAzure architecture
Azure architecture
 
Design patterns for microservice architecture
Design patterns for microservice architectureDesign patterns for microservice architecture
Design patterns for microservice architecture
 
Introduction To Microservices
Introduction To MicroservicesIntroduction To Microservices
Introduction To Microservices
 
Log analytics with ELK stack
Log analytics with ELK stackLog analytics with ELK stack
Log analytics with ELK stack
 
Microservice vs. Monolithic Architecture
Microservice vs. Monolithic ArchitectureMicroservice vs. Monolithic Architecture
Microservice vs. Monolithic Architecture
 

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

Integrated Services for Web Applications
Integrated Services for Web ApplicationsIntegrated Services for Web Applications
Integrated Services for Web ApplicationsSaltmarch Media
 
Bare-Bones Software Architecture
Bare-Bones Software ArchitectureBare-Bones Software Architecture
Bare-Bones Software ArchitectureJohannes Brodwall
 
Kineo Moodle & Totara User Group Event (July 2012)
Kineo Moodle & Totara User Group Event (July 2012)Kineo Moodle & Totara User Group Event (July 2012)
Kineo Moodle & Totara User Group Event (July 2012)Kineo
 
CIS 2015 SCIM in the Real World - Kelly Grizzle
CIS 2015 SCIM in the Real World -  Kelly GrizzleCIS 2015 SCIM in the Real World -  Kelly Grizzle
CIS 2015 SCIM in the Real World - Kelly GrizzleCloudIDSummit
 
SCIM in the Real World: Adoption is Growing
SCIM in the Real World: Adoption is GrowingSCIM in the Real World: Adoption is Growing
SCIM in the Real World: Adoption is GrowingKelly Grizzle
 
Lecture 11 managing the network
Lecture 11   managing the networkLecture 11   managing the network
Lecture 11 managing the networkWiliam Ferraciolli
 
Managed Beans: When, Why and How
Managed Beans: When, Why and HowManaged Beans: When, Why and How
Managed Beans: When, Why and HowRussell Maher
 
Oracle Enterprise Manager Security: A Practitioners Guide
Oracle Enterprise Manager Security: A Practitioners GuideOracle Enterprise Manager Security: A Practitioners Guide
Oracle Enterprise Manager Security: A Practitioners GuideCourtney Llamas
 
Migrating and Modernizing Identity on the Path to Multi Cloud
Migrating and Modernizing Identity on the Path to Multi CloudMigrating and Modernizing Identity on the Path to Multi Cloud
Migrating and Modernizing Identity on the Path to Multi CloudStrata Identity
 
Sim-webcast-part1-1aa
Sim-webcast-part1-1aaSim-webcast-part1-1aa
Sim-webcast-part1-1aaOracleIDM
 
Hitachi ID Identity Manager: Detailed presentation
Hitachi ID Identity Manager: Detailed presentationHitachi ID Identity Manager: Detailed presentation
Hitachi ID Identity Manager: Detailed presentationHitachi ID Systems, Inc.
 
Master IAM in the Cloud with SCIM v2.0
Master IAM in the Cloud with SCIM v2.0Master IAM in the Cloud with SCIM v2.0
Master IAM in the Cloud with SCIM v2.0Kelly Grizzle
 
2019-Nov: Domain Driven Design (DDD) and when not to use it
2019-Nov: Domain Driven Design (DDD) and when not to use it2019-Nov: Domain Driven Design (DDD) and when not to use it
2019-Nov: Domain Driven Design (DDD) and when not to use itMark Windholtz
 
Towards a Modularity Maturity Model
Towards a Modularity Maturity ModelTowards a Modularity Maturity Model
Towards a Modularity Maturity ModelGraham Charters
 
Adm 201 study group session 1 user interface kathy c
Adm 201 study group session 1   user interface kathy cAdm 201 study group session 1   user interface kathy c
Adm 201 study group session 1 user interface kathy covalisgroup
 
Adm 201 study group session 1 user interface kathy c
Adm 201 study group session 1   user interface kathy cAdm 201 study group session 1   user interface kathy c
Adm 201 study group session 1 user interface kathy covalisgroup
 
Domain Driven Design - Building Blocks
Domain Driven Design - Building BlocksDomain Driven Design - Building Blocks
Domain Driven Design - Building BlocksMark Windholtz
 
CDI Best Practices with Real-Life Examples - TUT3287
CDI Best Practices with Real-Life Examples - TUT3287CDI Best Practices with Real-Life Examples - TUT3287
CDI Best Practices with Real-Life Examples - TUT3287Ahmad Gohar
 

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

Integrated Services for Web Applications
Integrated Services for Web ApplicationsIntegrated Services for Web Applications
Integrated Services for Web Applications
 
Bare-Bones Software Architecture
Bare-Bones Software ArchitectureBare-Bones Software Architecture
Bare-Bones Software Architecture
 
Kineo Moodle & Totara User Group Event (July 2012)
Kineo Moodle & Totara User Group Event (July 2012)Kineo Moodle & Totara User Group Event (July 2012)
Kineo Moodle & Totara User Group Event (July 2012)
 
CIS 2015 SCIM in the Real World - Kelly Grizzle
CIS 2015 SCIM in the Real World -  Kelly GrizzleCIS 2015 SCIM in the Real World -  Kelly Grizzle
CIS 2015 SCIM in the Real World - Kelly Grizzle
 
SCIM in the Real World: Adoption is Growing
SCIM in the Real World: Adoption is GrowingSCIM in the Real World: Adoption is Growing
SCIM in the Real World: Adoption is Growing
 
Lecture 11 managing the network
Lecture 11   managing the networkLecture 11   managing the network
Lecture 11 managing the network
 
Managed Beans: When, Why and How
Managed Beans: When, Why and HowManaged Beans: When, Why and How
Managed Beans: When, Why and How
 
Oracle Enterprise Manager Security: A Practitioners Guide
Oracle Enterprise Manager Security: A Practitioners GuideOracle Enterprise Manager Security: A Practitioners Guide
Oracle Enterprise Manager Security: A Practitioners Guide
 
Migrating and Modernizing Identity on the Path to Multi Cloud
Migrating and Modernizing Identity on the Path to Multi CloudMigrating and Modernizing Identity on the Path to Multi Cloud
Migrating and Modernizing Identity on the Path to Multi Cloud
 
Agile Architecture
Agile ArchitectureAgile Architecture
Agile Architecture
 
Sim-webcast-part1-1aa
Sim-webcast-part1-1aaSim-webcast-part1-1aa
Sim-webcast-part1-1aa
 
Hitachi ID Identity Manager: Detailed presentation
Hitachi ID Identity Manager: Detailed presentationHitachi ID Identity Manager: Detailed presentation
Hitachi ID Identity Manager: Detailed presentation
 
Master IAM in the Cloud with SCIM v2.0
Master IAM in the Cloud with SCIM v2.0Master IAM in the Cloud with SCIM v2.0
Master IAM in the Cloud with SCIM v2.0
 
2019-Nov: Domain Driven Design (DDD) and when not to use it
2019-Nov: Domain Driven Design (DDD) and when not to use it2019-Nov: Domain Driven Design (DDD) and when not to use it
2019-Nov: Domain Driven Design (DDD) and when not to use it
 
Towards a Modularity Maturity Model
Towards a Modularity Maturity ModelTowards a Modularity Maturity Model
Towards a Modularity Maturity Model
 
Adm 201 study group session 1 user interface kathy c
Adm 201 study group session 1   user interface kathy cAdm 201 study group session 1   user interface kathy c
Adm 201 study group session 1 user interface kathy c
 
Adm 201 study group session 1 user interface kathy c
Adm 201 study group session 1   user interface kathy cAdm 201 study group session 1   user interface kathy c
Adm 201 study group session 1 user interface kathy c
 
Domain Driven Design - Building Blocks
Domain Driven Design - Building BlocksDomain Driven Design - Building Blocks
Domain Driven Design - Building Blocks
 
CDI Best Practices with Real-Life Examples - TUT3287
CDI Best Practices with Real-Life Examples - TUT3287CDI Best Practices with Real-Life Examples - TUT3287
CDI Best Practices with Real-Life Examples - TUT3287
 
DITA Interoperability
DITA InteroperabilityDITA Interoperability
DITA Interoperability
 

Último

Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 

Último (20)

Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 

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

  • 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. © 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. © 2019, Domain Driven Design Taiwan Community Source: Domain-Driven Design Reference by Evans
  • 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. © 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. © 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. © 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. © 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. © 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. © 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. © 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. © 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. © 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. © 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. © 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. © 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. © 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. © 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. © 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. © 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. © 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. © 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. © 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. © 2019, Domain Driven Design Taiwan Community User behavior:
  • 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. © 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. © 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. © 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. © 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. © 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. © 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. © 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. © 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. © 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. © 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. © 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. © 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. © 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. © 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. © 2019, Domain Driven Design Taiwan Community Workshop example project: Domain model
  • 41. © 2019, Domain Driven Design Taiwan Community • Notice “address” related operations added for Freelancer • Freelancer moved to new location address
  • 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. © 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. © 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. © 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. © 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. © 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. © 2019, Domain Driven Design Taiwan Community Q & A