SlideShare uma empresa Scribd logo
1 de 48
Baixar para ler offline
© 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

Mais conteúdo relacionado

Mais procurados

REST Service Authetication with TLS & JWTs
REST Service Authetication with TLS & JWTsREST Service Authetication with TLS & JWTs
REST Service Authetication with TLS & JWTsJon Todd
 
[115]쿠팡 서비스 클라우드 마이그레이션 통해 배운것들
[115]쿠팡 서비스 클라우드 마이그레이션 통해 배운것들[115]쿠팡 서비스 클라우드 마이그레이션 통해 배운것들
[115]쿠팡 서비스 클라우드 마이그레이션 통해 배운것들NAVER D2
 
Securing APIs with Open Policy Agent
Securing APIs with Open Policy AgentSecuring APIs with Open Policy Agent
Securing APIs with Open Policy AgentNordic APIs
 
MuleSoft Surat Meetup#44 - Anypoint Flex Gateway Custom Policies With Rust
MuleSoft Surat Meetup#44 - Anypoint Flex Gateway Custom Policies With RustMuleSoft Surat Meetup#44 - Anypoint Flex Gateway Custom Policies With Rust
MuleSoft Surat Meetup#44 - Anypoint Flex Gateway Custom Policies With RustJitendra Bafna
 
An Introduction to the AWS Well Architected Framework - Webinar
An Introduction to the AWS Well Architected Framework - WebinarAn Introduction to the AWS Well Architected Framework - Webinar
An Introduction to the AWS Well Architected Framework - WebinarAmazon Web Services
 
클라우드 네이티브 IT를 위한 4가지 요소와 상관관계 - DevOps, CI/CD, Container, 그리고 MSA
클라우드 네이티브 IT를 위한 4가지 요소와 상관관계 - DevOps, CI/CD, Container, 그리고 MSA클라우드 네이티브 IT를 위한 4가지 요소와 상관관계 - DevOps, CI/CD, Container, 그리고 MSA
클라우드 네이티브 IT를 위한 4가지 요소와 상관관계 - DevOps, CI/CD, Container, 그리고 MSAVMware Tanzu Korea
 
Best Practices of Infrastructure as Code with Terraform
Best Practices of Infrastructure as Code with TerraformBest Practices of Infrastructure as Code with Terraform
Best Practices of Infrastructure as Code with TerraformDevOps.com
 
Running Mission Critical Workloads on AWS
Running Mission Critical Workloads on AWSRunning Mission Critical Workloads on AWS
Running Mission Critical Workloads on AWSAmazon Web Services
 
Event Driven Architecture
Event Driven ArchitectureEvent Driven Architecture
Event Driven ArchitectureChris Patterson
 
Open Policy Agent Deep Dive Seattle 2018
Open Policy Agent Deep Dive Seattle 2018Open Policy Agent Deep Dive Seattle 2018
Open Policy Agent Deep Dive Seattle 2018Torin Sandall
 
Creating AWS infrastructure using Terraform
Creating AWS infrastructure using TerraformCreating AWS infrastructure using Terraform
Creating AWS infrastructure using TerraformKnoldus Inc.
 
Big Data Redis Mongodb Dynamodb Sharding
Big Data Redis Mongodb Dynamodb ShardingBig Data Redis Mongodb Dynamodb Sharding
Big Data Redis Mongodb Dynamodb ShardingAraf Karsh Hamid
 
AZ-204: Monitor, Troubleshoot & Optimize Azure Solutions
AZ-204: Monitor, Troubleshoot & Optimize Azure SolutionsAZ-204: Monitor, Troubleshoot & Optimize Azure Solutions
AZ-204: Monitor, Troubleshoot & Optimize Azure SolutionsAzureEzy1
 
Amazon Personalize 개인화 추천 모델 만들기::김태수, 솔루션즈 아키텍트, AWS::AWS AIML 스페셜 웨비나
Amazon Personalize 개인화 추천 모델 만들기::김태수, 솔루션즈 아키텍트, AWS::AWS AIML 스페셜 웨비나Amazon Personalize 개인화 추천 모델 만들기::김태수, 솔루션즈 아키텍트, AWS::AWS AIML 스페셜 웨비나
Amazon Personalize 개인화 추천 모델 만들기::김태수, 솔루션즈 아키텍트, AWS::AWS AIML 스페셜 웨비나Amazon Web Services Korea
 

Mais procurados (20)

REST Service Authetication with TLS & JWTs
REST Service Authetication with TLS & JWTsREST Service Authetication with TLS & JWTs
REST Service Authetication with TLS & JWTs
 
[115]쿠팡 서비스 클라우드 마이그레이션 통해 배운것들
[115]쿠팡 서비스 클라우드 마이그레이션 통해 배운것들[115]쿠팡 서비스 클라우드 마이그레이션 통해 배운것들
[115]쿠팡 서비스 클라우드 마이그레이션 통해 배운것들
 
Securing APIs with Open Policy Agent
Securing APIs with Open Policy AgentSecuring APIs with Open Policy Agent
Securing APIs with Open Policy Agent
 
Open Policy Agent
Open Policy AgentOpen Policy Agent
Open Policy Agent
 
MuleSoft Surat Meetup#44 - Anypoint Flex Gateway Custom Policies With Rust
MuleSoft Surat Meetup#44 - Anypoint Flex Gateway Custom Policies With RustMuleSoft Surat Meetup#44 - Anypoint Flex Gateway Custom Policies With Rust
MuleSoft Surat Meetup#44 - Anypoint Flex Gateway Custom Policies With Rust
 
An Introduction to the AWS Well Architected Framework - Webinar
An Introduction to the AWS Well Architected Framework - WebinarAn Introduction to the AWS Well Architected Framework - Webinar
An Introduction to the AWS Well Architected Framework - Webinar
 
Terraform
TerraformTerraform
Terraform
 
IAM Best Practices
IAM Best PracticesIAM Best Practices
IAM Best Practices
 
클라우드 네이티브 IT를 위한 4가지 요소와 상관관계 - DevOps, CI/CD, Container, 그리고 MSA
클라우드 네이티브 IT를 위한 4가지 요소와 상관관계 - DevOps, CI/CD, Container, 그리고 MSA클라우드 네이티브 IT를 위한 4가지 요소와 상관관계 - DevOps, CI/CD, Container, 그리고 MSA
클라우드 네이티브 IT를 위한 4가지 요소와 상관관계 - DevOps, CI/CD, Container, 그리고 MSA
 
Best Practices of Infrastructure as Code with Terraform
Best Practices of Infrastructure as Code with TerraformBest Practices of Infrastructure as Code with Terraform
Best Practices of Infrastructure as Code with Terraform
 
Amazon ECS
Amazon ECSAmazon ECS
Amazon ECS
 
Running Mission Critical Workloads on AWS
Running Mission Critical Workloads on AWSRunning Mission Critical Workloads on AWS
Running Mission Critical Workloads on AWS
 
Event Driven Architecture
Event Driven ArchitectureEvent Driven Architecture
Event Driven Architecture
 
Setting Up a Landing Zone
Setting Up a Landing ZoneSetting Up a Landing Zone
Setting Up a Landing Zone
 
Multi Cloud Architecture Approach
Multi Cloud Architecture ApproachMulti Cloud Architecture Approach
Multi Cloud Architecture Approach
 
Open Policy Agent Deep Dive Seattle 2018
Open Policy Agent Deep Dive Seattle 2018Open Policy Agent Deep Dive Seattle 2018
Open Policy Agent Deep Dive Seattle 2018
 
Creating AWS infrastructure using Terraform
Creating AWS infrastructure using TerraformCreating AWS infrastructure using Terraform
Creating AWS infrastructure using Terraform
 
Big Data Redis Mongodb Dynamodb Sharding
Big Data Redis Mongodb Dynamodb ShardingBig Data Redis Mongodb Dynamodb Sharding
Big Data Redis Mongodb Dynamodb Sharding
 
AZ-204: Monitor, Troubleshoot & Optimize Azure Solutions
AZ-204: Monitor, Troubleshoot & Optimize Azure SolutionsAZ-204: Monitor, Troubleshoot & Optimize Azure Solutions
AZ-204: Monitor, Troubleshoot & Optimize Azure Solutions
 
Amazon Personalize 개인화 추천 모델 만들기::김태수, 솔루션즈 아키텍트, AWS::AWS AIML 스페셜 웨비나
Amazon Personalize 개인화 추천 모델 만들기::김태수, 솔루션즈 아키텍트, AWS::AWS AIML 스페셜 웨비나Amazon Personalize 개인화 추천 모델 만들기::김태수, 솔루션즈 아키텍트, AWS::AWS AIML 스페셜 웨비나
Amazon Personalize 개인화 추천 모델 만들기::김태수, 솔루션즈 아키텍트, AWS::AWS AIML 스페셜 웨비나
 

Semelhante 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
 

Semelhante 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
 
Introduction to DDD
Introduction to DDDIntroduction to DDD
Introduction to DDD
 
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
 

Último

Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Hararemasabamasaba
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfkalichargn70th171
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyviewmasabamasaba
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...masabamasaba
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburgmasabamasaba
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...masabamasaba
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationShrmpro
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durbanmasabamasaba
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 

Último (20)

Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions Presentation
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 

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