SlideShare ist ein Scribd-Unternehmen logo
1 von 110
ARAF KARSH HAMID
Co-Founder / CTO
MetaMagic Global Inc., NJ, USA
@arafkarsh
arafkarsh
Domain
Driven
Design
Agenda
2
• Hexagonal Architecture
• Shopping Portal Example
Hexagonal Architecture4
• Ubiquitous Language
• Bounded Context
• Context Maps
Domain Driven Design – Strategic Design1
• Shopping Portal App
• Specification Guidelines
• Implementation Guidelines
Case Study5
• Aggregate Roots
• Entities / Value Objects
• Factories
• Repositories
• Domain Events
• Domain Service
Domain Driven Design – Tactical Design2
• Object Modeling to Process Modeling
• Capability Centric Design
• Domain and Integration Events
• Event Storming Concept and Diagrams
• Event Storming Examples
Event Storming3
• Monolithic to Microservices
• Capability Centric Design
Monolithic App0
Monolithic > Microservices
• FORRESTER RESEARCH
• MODERNIZATION JOURNEY
• ASSESS AND CLASSIFY YOUR APP PORTFOLIO
• PLAN AND PRIORITIZE
3
Conway’s Law
4
Any Organization that designs a system
(defined broadly) will produce a design
whose structure is a copy of the
organization’s communication structure.
0
* For IT Services : They can do one more project of same size with ZERO COST in Platform Licensing (Based on 20 developer pack USD $50K per month for 3 months License cost = $150K)
5
0
Scale Cube and Micro Services
6
1. Y Axis Scaling – Functional Decomposition : Business Function as a Service
2. Z Axis Scaling – Database Partitioning : Avoid locks by Database Sharding
3. X Axis Scaling – Cloning of Individual Services for Specific Service Scalability
0
Modernization Journey
7
 Start new features as Microservices
Incrementally establish the success early.
 Expose Legacy On-Premise Apps API’s
If legacy Apps cant be shifted to Cloud
 Refactor Monolithic features to Microservices
Breakdown and Deploy Feature by Feature
 Containerize the Microservice
Reduce costs, simplifies the operations and consistent
environment between Dev, QA and Production
 Monolith De-commission Plan
Incrementally sunset the Monolith
Velocity as you
transform
Increase your
Delivery Velocity
along the
Journey
High
FuturePresent
Low
Inspired by a paper from IBM
0
Assess and Classify your App Portfolio
8
 Take inventory of your Apps
Classify the Apps based on
technology, complexity.
 Align Apps to your Business
Priorities
Identify the Apps that are critical for
Modernization.
 Identify Business
Modernization Requirements
Create a Roadmap with faster go to
market strategy
 Understand the effort and
Cost
Evaluate all possible Modernization
options
Container Refactor Expose APIsLift & Shift
BusinessValueCostComplexity
Product Catalogue
Product Review
Inventory Shopping Cart
Customer
Profile
Order Management
Inspired by a paper from IBM
0
Plan and Prioritize
9
Complexity Cost Value Score Rank
Weightage 35% 25% 40%
Customer
Med
3
Med
3
Low
1
2.20
7
6
Product
Reviews
Med
3
High
5
Med
3
3.50
11
3
Product
Catalogue
Med
3
Med
3
High
5
4.80
11
1
Shopping
Cart
High
5
Med
3
Med
3
3.70
11
4
Order
Very High
7
Med
3
High
5
5.20
15
2
Inventory
Very High
7
High
5
Med
3
4.90
15
5
 Prioritize
Low Priority projects are
good test cases but does not
bring much business value.
 Quick Wins
Identify a feature / project
which has good business
value and low in complexity.
 Project Duration
Focus on shorter duration
projects with high Business
Value.
Shopping Portal Features Prioritization
Inspired by a paper from IBM
0
Monolithic to Microservices Summary
10
1. Classify your Apps into Following areas
1. Lift and Shit
2. Containerize
3. Refactor
4. Expose API
2. Prioritize High Business Value Low Technical
Complexity
3. Focus on Shorter Duration – From Specs to Operation
0
CAPABILITY CENTRIC DESIGN
• BUSINESS FUNCTIONS
• BUSINESS PROCESS
• TEAM STRUCTURE
11
Business Solution & Business Process
12
 Business Solution focuses the entire Journey of the User which
can run across multiple Microservices.
 Business Solution comprises a set of Business Processes.
 A specific Microservice functionality will be focused on a
Business Process / Concern
 Business Process can be divided further into Business Functions
Business Solution: Customer Dining Experience
Order PaymentFood Menu KitchenDining
Browse Menu Order Dinner Dinner Served Get Bill Make Payment
0
Capability Centric Design
13
Vertically sliced Product Team
Business Centric Development
• Focus on Business Capabilities
• Entire team is aligned towards
Business Capability.
• From Specs to Operations – The
team handles the entire spectrum
of Software development.
• Every vertical will have it’s own
Code Pipeline
Front-End-Team Back-End-Team Database-Team
In a typical Monolithic way the team is
divided based on technology / skill set
rather than business functions. This leads
to not only bottlenecks but also lack of
understanding of the Business Domain.
QA / QC Team
Front-End
Back-End
Database
Business
Capability 1
QA/QCTeam
Front-End
Back-End
Database
Business
Capability 2
QA/QCTeam
Front-End
Back-End
Database
Business
Capability 3
QA/QCTeam
0
14
From
Project Based
Activity
Oriented
To
Product Based
Outcome
Oriented
Source: Sriram Narayan– https://martinfowler.com/bliki/BusinessCapabilityCentric.html
0
Capability Centric Design Summary
15
1. Business Solutions
2. Business Process
3. Business Capabilities
4. Business Driven Teams
(From Specs to Ops)
5. Outcome Oriented instead
of Activity Oriented.
0
Business Solution
Business
Process 1
Business
Process 2
Business
Process n
Business Capability 1
Business Capability 2
Business
Capability n
16
Domain Driven Design
• Strategic Design
• Tactical Design
o Ubiquitous Language
o Bounded Context
o Context Map
17
Ubiquitous
Language
Vocabulary shared by
all involved parties
Used in all forms of spoken /
written communication
Ubiquitous
Language
Domain
Expert
Analyst Developers
QA
Design
Docs
Test Cases
Code
Restaurant Context – Food Item :
Eg. Food Item (Navrathnakurma)
can have different meaning or
properties depends on the
context.
• In the Menu Context it’s a
Veg Dish.
• In the Kitchen Context it’s
is recipe.
• And in the Dining Context
it will have more info
related to user feed back
etc.
DDD: Ubiquitous Language: Strategic Design
As an Restaurant Owner
I want to know who my Customers are
So that I can serve them better
Role-Feature-Reason Matrix
BDD – Behavior Driven Development
Given Customer John Doe exists
When Customer orders food
Then
Assign customer preferences
as Veg or Non Veg customer
BDD Construct
Bounded Context – Strategic Design
18
1
• Bounded Context is a Specific Business Process / Concern.
• Components / Modules inside the Bounded Context are context specific.
• Multiple Bounded Contexts are linked using Context Mapping.
• One Team assigned to a Bounded Context.
• Each Bounded Context will have it’s own Source Code Repository.
• When the Bounded Context is being developed as a key strategic
initiative of your organization, it’s called the Core Domain.
• Within a Bounded Context the team must have same language called
Ubiquitous language for Spoken and for Design / Code Implementation.
DDD: Bounded Context – Strategic Design
19
An App User’s Journey can run across
multiple Bounded Context / Micro
Services.
Dinning
Order
Reservation
Tables
Recipes
Raw
Materials
Frozen
Semi Cooked
Appetizer Veg
Appetizer Non
Veg
Soft Drinks
Main Course
Non Veg
Main Course
Veg
Hot Drinks Desserts
Steward
Chef
Menu
uses
uses
Dinning
Order
Reservation
Tables
Recipes
Raw
Materials
Frozen
Semi Cooked
Appetizer Veg
Appetizer Non
Veg
Soft Drinks
Main Course
Non Veg
Main Course
Veg
Hot Drinks Desserts
Steward
Chef
Menu
uses
uses
UnderstandingBoundedContext(DDD)ofaRestaurantApp
Dinning
Context
Kitchen
Context
Menu Context
Source: Domain-Driven Design
Reference by Eric Evans
1
Areas of the domain treated
independently
Discovered as you assess
requirements and build language
Bounded
Context
Bounded
Context
Bounded
Context
User Journey X
20
DDD : Understanding Bounded Context1
Source: Patterns, Principles and Practices of DDD – Page 124
This model shows multiple
responsibilities of the
shared Model – Product.
This is a classic example of
Big Ball of Mud.
21
DDD : Understanding Bounded Context1
Source: Patterns, Principles and Practices of DDD – Page 127 Each of this context will become a Microservice
22
DDD : Understanding Bounded Context
Source: BoundedContext By Martin Fowler :
http://martinfowler.com/bliki/BoundedContext.html
• DDD deals with large models by
dividing them into different
Bounded Contexts and being explicit
about their interrelationships.
• Bounded Contexts have both
unrelated concepts
• Such as a support ticket only
existing in a customer support
context
• But also share concepts such as
products and customers.
• Different contexts may have
completely different models of
common concepts (Customer &
Product) with mechanisms to map
between these polysemic concepts
for integration.
1
Customer Model in Different Bounded Context
23
Order
Customer
• Customer ID
• Discount
• Bonus Program
Delivery
Customer
• Customer ID
• Address
• Preferred
Delivery method
• Packaging
• Delivery Contact
Billing
Customer
• Customer ID
• Billing Address
• Payment Type
• Tax
o Customer Model has different attributes in different contexts. So it avoids
storing all the customer info in one place and then sharing that across
multiple Bounded Contexts (Microservices).
o If you want to change Customer details related to Tax then only Billing
Bounded Context (Microservice) needs to be updated.
1
24
DDD : Understanding Bounded Context1
Source: Patterns, Principles and Practices of DDD – Page 132
Each of this Bounded Context
will become a Microservice
Communication across Bounded Context
Source: Patterns, Principles and Practices of DDD – Page 203
25
DDD : Understanding Bounded Context1
Source: Patterns, Principles and Practices of DDD – Page 157
Microservice is a Bounded Context
DDD : Context Map
26
Source: Domain-Driven Design Reference by Eric Evans
1
(C) COPYRIGHT METAMAGIC GLOBAL INC., NEW JERSEY, USA
DDD : Understanding Context Map
1. A context map provides Global View of the system that UML or architecture diagrams completely
miss, helping us to focus on choices that are really viable in your scenario without wasting money.
2. Each Bounded Context fits within the Context Map to show how they should communicate amongst
each other and how data should be shared.
27
Up Stream (u) – Down Stream (d)
The upstream team may succeed independently of the
fate of the downstream team.
Mutually Dependent
Success depends on the success of both the teams.
Free
In which success or failure of the development work in
other contexts has little affect on delivery.
1
DDD: Context Map
28
Term Definition Action
Partnership When teams in two context will succeed or fail together, a
cooperative relationship often emerges.
Forge Partnerships
Shared Kernel Sharing a part of the Mode and associated code is very
intimate interdependency, which can leverage design work
or undermine it.
Keep the Kernel Small.
Customer /
Supplier
When two teams are in upstream – downstream
relationship, where the upstream team may succeed
independently of the fate of the downstream team, the
needs of the downstream come to be addressed in a
variety of ways with wide range of consequences.
Downstream priorities factor
into upstream planning.
Conformist Upstream has no motivation in this partnership to keep
the promise. Altruism may motivate Upstream developers
to give promises they cant keep.
Share just enough info with
upstream to keep their
motivation.
Anti
Corruption
Layer
When the translation between two bounded context
becomes more complex, then the translation layer takes
on a more defensive tone.
(down stream) creates a layer in
sync own model and matching
(up stream) functionality.
1
DDD: Context Map
29
Term Definition Action
Open Host
Service
When a subsystem has to be integrated with many others,
customizing a translator for each can bog down the team. There is
more and more to maintain, and more and more to worry about
when changes are made.
Use a one of
translator to augment
the Protocol to share
info (REST)
Published
Language
Translation between the models of two bounded contexts requires
a common language.
Published Language is often combined with Open Host Service.
Use a well
documented shared
language (JSON)
Separate Ways If two sets of functionality have no significant relationship, they
can be completely cut loose from each other. Integration is always
expensive and sometimes the benefit is small.
Bounded context with
no connection to
others.
Big Ball of
Mud
As we survey existing systems, we find that, in fact, there are parts
of systems, often large ones, where models are mixed and
boundaries are inconsistent.
Designate the mess as
a Big Ball of Mud.
1
Context Map – Coordination Efforts
30
Shared Bounded Context
Shared Kernel
Customer / Supplier
Published Language
Open Host Service
Anticorruption Layer
Conformist
Separate Ways
Coordination
Effort
1
DDD: Strategic Design Patterns
31
Pattern Description Page
1
Bounded
Context
They are
NOT
Modules
A Bounded Context delimits the applicability of a particular model so that the team
members have a clear and shared understanding of what has to be consistent and how it
relates to other Contexts. Contexts can be created from (but not limited to) the following:
• how teams are organized
• the structure and layout of the code base
• usage within a specific part of the domain
335
2 Context Map
Context mapping is a design process where the contact points and translations between
bounded contexts are explicitly mapped out. Focus on mapping the existing landscape,
and deal with the actual transformations later.
1. Shared Kernel
2. Customer / Supplier
3. Conformist
4. Anti Corruption Layer
5. Separate Ways
3
Specification
Pattern
Use the specification pattern when there is a need to model rules, validation and selection
criteria. The specification implementations test whether an object satisfies all the rules of
the specification.
4
Strategy
Pattern
The strategy pattern, also known as the Policy Pattern is used to make algorithms
interchangeable. In this pattern, the varying 'part' is factored out.
5
Composite
Pattern
This is a direct application of the GoF pattern within the domain being modeled. The
important point to remember is that the client code should only deal with the abstract
type representing the composite element.
Page Number from Domain Driven Design
– Published in 2015
1
Common Problems
32
1
1. Trying to make a perfect Boundary for the
Context.
2. Overemphasizing the importance of Tactical
Design Patterns
3. Using the same architecture for all Bounded
Contexts
4. Neglecting the Strategic Design Patterns
5. Focusing on Code rather than the principles of
DDD
33
Domain Driven Design
• Strategic Design
• Tactical Design
o Entity
o Value Object
o Aggregate Root
o Factory
o Repository
o Domain Service
o Domain Events
Domain Driven Design
34
Source: Domain-Driven Design Reference by Eric Evans
2
Layered Architecture
35
2
• Explicit Domain Models – Isolate your models from UI, Business
Logic.
• Domain Objects – Free of the Responsibility of displaying
themselves or storing themselves or managing App Tasks.
• Zero Dependency on Infrastructure, UI and Persistent Layers.
• Use Dependency Injection for Loosely Coupled Objects.
• All the Code for Domain Model in a Single Layer.
• Domain Model should be Rich enough to represent Business
Knowledge.
Source: DDD Reference by Chris Evans Page 17
Entity
36
2
Entities are Domain Concepts with
Identity and Continuity and can be
stored in a database.
Identity Examples of an Entity
• Order ID in Order Entity
• Social Security Number in Person
Entity
• Shipping ID in Shipping Address
Entity
• Order (Aggregate Root)
• Order Item
• Shipping Address
• Payment
Value Objects
37
2
Value Object
• Currency
• Item Value
• Order Status
• Payment Type
• Record State
• Audit Log
Value object represent a specific
business concept related that
Bounded Context in that Sub-
domain.
Value objects doesn’t have any
specific identity and it’s not
stored in the database.
It exists as part of an Entity.
Understanding Aggregate Root
38
Order
Customer
Shipping
Address
Aggregate
Root
Line Item
Line Item
Line Item
*
Payment
Strategy
Credit Card
Cash
Bank Transfer
Source: Martin Fowler : Aggregate Root
• An aggregate will have one of its component
objects be the aggregate root. Any references
from outside the aggregate should only go to the
aggregate root. The root can thus ensure the
integrity of the aggregate as a whole.
• Aggregates are the basic element of transfer of
data storage - you request to load or save whole
aggregates. Transactions should not cross
aggregate boundaries.
• Aggregates are sometimes confused with
collection classes (lists, maps, etc.).
• Aggregates are domain concepts (order, clinic visit,
playlist), while collections are generic. An
aggregate will often contain multiple collections,
together with simple fields.
125
Domain
Driven
Design
(C) COPYRIGHT METAMAGIC GLOBAL INC., NEW JERSEY, USA
2
Designing and Fine Tuning Aggregate Root
39
Source : Effective Aggregate Design Part 1/2/3 : Vaughn Vernon
http://dddcommunity.org/wp-content/uploads/files/pdf_articles/Vernon_2011_1.pdf
Aggregate Root - #1 Aggregate Root - #2
Super Dense Single Aggregate Root
Results in Transaction concurrency issues.
Super Dense Aggregate Root is split into 4
different smaller Aggregate Root in the 2nd
Iteration.
Working on different design models helps the developers to come up with best
possible design.
(C) COPYRIGHT METAMAGIC GLOBAL INC., NEW JERSEY, USA
2
40
Rules for Building Aggregate Roots
1. Protect True Invariants in Consistency Boundaries. This rule has the
added implication that you should modify just one Aggregate instance in a single
transaction. In other words, when you are designing an Aggregate composition,
plan on that representing a transaction boundary.
2. Design Small Aggregates. The smallest Aggregate you can design is one with a
single Entity, which will serve as the Aggregate Root.
3. Reference Other Aggregates Only By Identity.
4. Use Eventual Consistency Outside the Consistency Boundary. This means that
ONLY ONE Aggregate instance will be required to be updated in a single
transaction. All other Aggregate instances that must be updated as a result of any
one Aggregate instance update can be updated within some time frame (using a
Domain Event). The business should determine the allowable time delay.
5. Build Unidirectional Relationship from the Aggregate Root.
2
Domain Services
41
2
Domain Services focuses bringing
the Behavior to your Domain
involving Entities and Value
Objects.
It focuses on a Single Responsibility.
Implementation of the Domain
Service resides in the service layer
and not in the Domain Layer.
Domain Layer
• Models
• Repo
• Services
• Factories
Adapters
• Repo
• Services
• Web Services
Domain Events & Integration Events
42
1. Domain Events represent something happened in a specific Domain.
2. Domain Events should be used to propagate STATE changes across
Multiple Aggregates within the Bounded Context.
3. The purpose of Integration Events is to propagate committed
transactions and updates to additional subsystems, whether they are
other microservices, Bounded Contexts or even external applications.
Source: Domain Events : Design and Implementation – Microsoft Docs – May 26, 2017
Domain
Data Behavior
Order (Aggregate Root)
Data Behavior
Address (Value Object)
Data Behavior
OrderItem (Child)
1
n
1
1
Order Created
Domain Event
Domain Layer
Enforce consistency
with other Aggregates
Event Handler 1
Event Handler n
Create and Publish Integration
Event to Event Bus.
Example: Order Placed
Integration Event can be
subscribed by Inventory system
to update the Inventory details.
Event Handler 2
2
Communication Synchronous – RPC
43
2
Source: Patterns, Principles and Practices of DDD – Page 212
Communication Async – Event Based
44
2
Source: Patterns, Principles and Practices of DDD – Page 217
Reactive Programming Comparison : Iterable / Streams / Observable
45
First Class Visitor (Consumer)
Serial Operations
Parallel Streams (10x Speed)
Still On Next, On Complete and
On Error are Serial Operations
Completely Asynchronous
Operations
Java 8 – Blocking CallJava 6 – Blocking Call Rx Java - Freedom
2
Reactive Programming RxJava Operator : Filter / Sort / FlatMap
46
Objective:
toSortedList() returns an Observable with a single List containing Fruits.
Using FlatMap to Transform Observable <List> to Observable <Fruit>
Rx Example 2
2
Data Transfer Object vs. Value Object
47
Data Transfer Object Value Object
A DTO is just a data container which is used
to transport data between layers and tiers.
A Value Object represents itself a fix set of
data and is similar to a Java enum.
It mainly contains of attributes and it’s a
serializable object.
A Value Object doesn't have any identity, it is
entirely identified by its value and is
immutable.
DTOs are anemic in general and do not
contain any business logic.
A real world example would be Color.RED,
Color.BLUE, Currency.USD
Patterns of Enterprise Application Architecture : Martin Fowler
http://martinfowler.com/books/eaa.html
A small simple object, like money or a date range, whose equality isn’t based on identity.
486
P of EAA
Java EE 7 Retired the DTO
In Java EE the RS spec became the de-facto standard for remoting, so the implementation of
serializable interface is no more required. To transfer data between tiers in Java EE 7 you get the
following for FREE!
1. JAXB : Offer JSON / XML serialization for Free.
2. Java API for JSON Processing – Directly serialize part of the Objects into JSON
2
DTO – Data Transfer Object
Security Considerations
Data obtained from untrusted sources, such as user input from a Web page, should be cleansed and validated before being
placed into a DTO. Doing so enables you to consider the data in the DTO relatively safe, which simplifies future interactions
with the DTO.
48
The Problem Assembler Pattern
An object that carries data between processes in order to reduce the number of method calls.
Benefits
1. Reduced Number of Calls
2. Improved Performance
3. Hidden Internals
4. Discovery of Business
objects
Liabilities
1. Class Explosion
2. Additional Computation
3. Additional Coding Effort
https://msdn.microsoft.com/en-us/library/ms978717.aspx
Problem: How do you preserve the simple semantics of a procedure call interface without being
subject to the latency issues inherent in remote communication?
The Solution
401
P of EAA
2
DTO – Data Transfer Object
49
An object that carries data between processes in order to reduce the number of method calls.
The most misused pattern in the Java
Enterprise community is the DTO.
DTO was clearly defined as a solution for a
distribution problem.
DTO was meant to be a coarse-grained
data container which efficiently transports
data between processes (tiers).
On the other hand considering a dedicated
DTO layer as an investment, rarely pays off
and often lead to over engineered bloated
architecture.
Real World Java
EE Patterns
Adam Bien
http://realworldpatterns.com
Don't underestimate the cost of [using DTOs].... It's significant, and
it's painful - perhaps second only to the cost and pain of object-
relational mapping.
Another argument I've heard is using them in case you want to
distribute later. This kind of speculative distribution boundary is
what I rail against. Adding remote boundaries adds complexity.
One case where it is useful to use something like a DTO is when you
have a significant mismatch between the model in your presentation
layer and the underlying domain model.
In this case it makes sense to make presentation specific
facade/gateway that maps from the domain model and presents an
interface that's convenient for the presentation.
Patterns of Enterprise Application Architecture : Martin Fowler
http://martinfowler.com/books/eaa.html
401
P of EAA
2
50
Other subsystemAnti-corruption layer 365
Domain
Driven
Design
Your subsystem
2 Anti Corruption Layer – ACL
Repository Pattern
Objectives
Use the Repository pattern to achieve one or more of the following
objectives:
• You want to maximize the amount of code that can be tested with
automation and to isolate the data layer to support unit testing.
• You access the data source from many locations and want to apply
centrally managed, consistent access rules and logic.
• You want to implement and centralize a caching strategy for the data
source.
• You want to improve the code's maintainability and readability by
separating business logic from data or service access logic.
• You want to use business entities that are strongly typed so that you can
identify problems at compile time instead of at run time.
• You want to associate a behavior with the related data. For example, you
want to calculate fields or enforce complex relationships or business
rules between the data elements within an entity.
• You want to apply a domain model to simplify complex business logic.
51
Repository Pattern Source:
Martin Fowler : http://martinfowler.com/eaaCatalog/repository.html | Microsoft : https://msdn.microsoft.com/en-us/library/ff649690.aspx
Mediates between the domain and data mapping layers using a collection-
like interface for accessing domain objects.
322
P of EAA
Conceptually, a Repository encapsulates the set of objects
persisted in a data store and the operations performed over them,
providing a more object-oriented view of the persistence layer.
Repository also supports the objective of achieving a clean
separation and one-way dependency between the domain and
data mapping layers.
2
Anemic Domain Model : Anti Pattern
• There are objects, many named after the nouns in
the domain space, and these objects are connected
with the rich relationships and structure that true
domain models have.
• The catch comes when you look at the behavior, and
you realize that there is hardly any behavior on these
objects, making them little more than bags of
getters and setters.
• The fundamental horror of this anti-pattern is that
it's so contrary to the basic idea of object-oriented
design; which is to combine data and process
together.
• The anemic domain model is really just a procedural
style design, exactly the kind of thing that object
bigots like me (and Eric) have been fighting since our
early days in Smalltalk.
52
Source: Anemic Domain Model By Martin Fowler :
http://martinfowler.com/bliki/AnemicDomainModel.html
• lockUser()
• unlockUser()
• addAddress(String address)
• removeAddress(String address)
2
Procedural Design Vs. Domain Driven Design
53
1. Anemic Entity Structure
2. Massive IF Statements
3. Entire Logic resides in Service
Layer
4. Type Dependent calculations are
done based on conditional checks
in Service Layer
4
1
23
Source: http://www.javaworld.com/article/2078042/java-app-dev/domain-driven-design-with-java-ee-6.html
Domain Driven Design with Java EE 6
By Adam Bien | Javaworld
2
Polymorphic Business Logic inside a Domain object
54
Domain Driven Design with Java EE 6
By Adam Bien | Javaworld
Computation of the total cost
realized inside a rich
Persistent Domain Object
(PDO) and not inside a service.
This simplifies creating very
complex business rules.
Source: http://www.javaworld.com/article/2078042/java-app-dev/domain-driven-design-with-java-ee-6.html
2
Type Specific Computation in a Sub Class
55
Source: http://www.javaworld.com/article/2078042/java-app-dev/domain-driven-design-with-java-ee-6.html
We can change the
computation of the shipping
cost of a Bulky Item without
touching the remaining
classes.
Its easy to introduce a new
Sub Class without affecting
the computation of the total
cost in the Load Class.
Domain Driven Design with Java EE 6
By Adam Bien | Javaworld
of
2
Object Construction : Procedural Way Vs. Builder Pattern
56
Procedural Way Builder Pattern
Source: http://www.javaworld.com/article/2078042/java-app-dev/domain-driven-design-with-java-ee-6.html
Domain Driven Design with Java EE 6
By Adam Bien | Javaworld
2
DDD: Tactical Design Patterns
57
Pattern Description Page
6 Entity An object defined Primarily by its identity is called an Entity 91
-
Value Object
(Already
referred in P of
EAA)
Many Objects have no conceptual Identity. These objects describe the
characteristic of a thing.
97
7
Aggregate
Aggregate is a cluster of domain objects that can be treated as a Single
Unit. Example Order and Order Item.
125
Aggregate Root
An Aggregate will have one of its component object be the Aggregate
Root.
127
-
Repositories
(Already
referred in P of
EAA)
A Repository represents all objects of a certain type as a conceptual set.
It acts like a collection, except with more elaborate querying capabilities.
Objects of appropriate type are added and removed, and the machinery
behind the Repository inserts them or deletes them from the database.
This definition gathers a cohesive set of responsibilities for providing
access to the roots of Aggregates from early life cycle through the end.
147
8
Factory /
Builder Pattern
When creation of an Object, or an entire Aggregate, becomes
complicated or reveals too much of the internal structure, Factories
provides encapsulation.
136
Page Number from Domain Driven Design
– Published in 2015
2
DDD: Tactical Design Patterns
58
Pattern Description Page
9
Factory / Builder
Pattern
When creation of an Object, or an entire Aggregate, becomes
complicated or reveals too much of the internal structure,
Factories provides encapsulation.
136
10 Domain Service
A Service tends to be named of an Activity rather than an Entity.
1. The Operation relates to a domain concept that is not a natural
part of an Entity.
2. The interface is defined in terms of other elements of the
Domain Model
3. The operation is stateless
104
11
Anti – Corruption
Layer
(External
Integration)
Creating an isolating layer to provide clients with functionality in
terms of their own Domain Model. The layer talks to the other
system through its existing interface, requiring little or no
modification to the other system. Internally the Layer translates in
both directions as necessary between the two models.
365
12 Domain Events
A Domain Event is a full-fledged part of the Domain Model, a
representation of of something that happened in the Domain.
Explicit events that the domain experts wants to track and
notified of or which are associated with the state changes in
other Domain Models.
Page Number from Domain Driven Design
– Published in 2015
2
Shopping Portal
59
Order ContextModels
Value Object
• Currency
• Item Value
• Order Status
• Payment Type
• Record State
• Audit Log
Entity
• Order (Aggregate Root)
• Order Item
• Shipping Address
• Payment
DTO
• Order
• Order Item
• Shipping Address
• Payment
Domain Layer Adapters
• Order Repository
• Order Service
• Order Web Service
• Order Query Web Service
• Shipping Address Web Service
• Payment Web Service
Adapters Consists of Actual
Implementation of the Ports like
Database Access, Web Services
API etc.
Converters are used to convert
an Enum value to a proper
Integer value in the Database.
For Example Order Status
Complete is mapped to integer
value 100 in the database.
Services / Ports
• Order Repository
• Order Service
• Order Web Service
Utils
• Order Factory
• Order Status Converter
• Record State Converter
• Order Query Web Service
• Shipping Address Web Service
• Payment Web Service
2
DDD – Summary
60
1. Ubiquitous Language
2. Bounded Context
3. Context Map
4. Entity
5. Value Object
6. Aggregate Root
7. Factory
8. Repository Pattern
9. Domain Service
10. Domain Events
11. Data Transfer Object
More on Event Storming
2
61
Event Storming
• Object Modeling to Process Modeling
• Domain Events for State Change
• Event Storming Process
Mind Shift : From Object Modeling to Process Modeling
62
3
Developers with Strong Object Modeling experience
will have trouble making Events a first class citizen.
• How do I start Event Sourcing?
• Where do I Start on Event Sourcing / CQRS?
The Key is:
1. App User’s Journey
2. Business Process
3. Ubiquitous Language – DDD
4. Capability Centric Design
5. Outcome Oriented The Best tool to define your process and its tasks.
How do you define your End User’s Journey & Business Process?
• Think It
• Build It
• Run IT
Business Solution & Business Process
63
 Business Solution focuses the entire Journey of the User which
can run across multiple Micro Services.
 Business Solution comprises a set of Business Processes.
 Business Process focuses on a specific Micro Service and its
functionality.
Business Solution: Customer Dining Experience
Order PaymentFood Menu KitchenDining
Browse Menu Order Dinner Dinner Served Get Bill Make Payment
3
Domain Events & Integration Events
64
1. Domain Events represent something happened in a specific Domain.
2. Domain Events should be used to propagate STATE changes across
Multiple Aggregates within the Bounded Context.
3. The purpose of Integration Events is to propagate committed
transactions and updates to additional subsystems, whether they are
other microservices, Bounded Contexts or even external applications.
Source: Domain Events : Design and Implementation – Microsoft Docs – May 26, 2017
Domain
Data Behavior
Order (Aggregate Root)
Data Behavior
Address (Value Object)
Data Behavior
OrderItem (Child)
1
n
1
1
Order Created
Domain Event
Domain Layer
Enforce consistency
with other Aggregates
Event Handler 1
Event Handler n
Create and Publish Integration
Event to Event Bus.
Example: Order Placed
Integration Event can be
subscribed by Inventory system
to update the Inventory details.
Event Handler 2
3
65
Process
• Define your Business Processes. Eg. Various aspects of Order
Processing in an E-Commerce Site, Movie Ticket Booking,
Patient visit in Hospital.1
Commands • Define the Commands (End-User interaction with your App) to
execute the Process. Eg. Add Item to Cart is a Command.2
Event Sourced
Aggregate
• Current state of the Aggregate is always derived from the Event
Store. Eg. Shopping Cart, Order etc. This will be part of the Rich
Domain Model (Bounded Context) of the Micro Service.4
Projections
• Projections focuses on the View perspective of the Application.
As the Read & Write are different Models, you can have
different Projections based on your View perspective.
5
Write
Data
Read
Data
Events • Commands generates the Events to be stored in Event Store.
Eg. Item Added Event (in the Shopping Cart).3
Event Storming – Concept3
66
Event Sourcing Intro
Standard CRUD Operations – Customer Profile – Aggregate Root
Profile Created Title Updated New Address added
Derived
Notes Removed
Time T1 T2 T4T3
Event Sourcing and Derived Aggregate Root
Commands
1. Create Profile
2. Update Title
3. Add Address
4. Delete Notes
2
Events
1. Profile Created Event
2. Title Updated Event
3. Address Added Event
4. Notes Deleted Event
3
Current State of the
Customer Profile
4
Event store
Single Source of Truth
Greg
Young
3
Event Storming : Restaurant Dining Example – Customer Journey
67
Order Payment
• Add Drinks
• Add Food
• Update Food
Commands • Open Table
• Add Juice
• Add Soda
• Add Appetizer 1
• Add Appetizer 2
• Serve Drinks
• Prepare Food
• Serve Food
Events
• Drinks Added
• Food Added
• Food Updated
• Food Discontinued
• Table Opened
• Juice Added
• Soda Added
• Appetizer 1 Added
• Appetizer 2 Added
• Juice Served
• Soda Served
• Appetizer Served
• Food Prepared
• Food Served
• Prepare Bill
• Process
Payment
• Bill Prepared
• Payment Processed
• Payment Approved
• Payment Declined
• Cash Paid
When people arrive at the Restaurant and take a table, a Table is opened. They may then order drinks and
food. Drinks are served immediately by the table staff, however food must be cooked by a chef. Once the
chef prepared the food it can then be served. Table is closed when the bill is prepared.
Microservices
• Dinning Order
• Billable Order
Customer Journey thru Dinning Processes
Processes
Food Menu KitchenDining
• Remove Soda
• Add Food 1
• Add Food 2
• Place Order
• Close Table
• Remove Soda
• Food 1 Added
• Food 2 Added
• Order Placed
• Table Closed
ES Aggregate
3
2 4
1
The purpose of this example is to demonstrate the concept of ES / CQRS thru Event Storming principles.
3
Event Storming Process map – Concept
68
1. Define your User Journey.User Journey
DE
IE
Domain
Events
Integration
Events
7. Events
Event(s)Command
Micro
Service
3. Command & Event(s) BridgeC Commands execute the tasks required to complete the Business Process.
Aggregate
Root
4. Event Sourced Aggregate
Event Sourced Aggregate is derived from a Collection of Events &
Factory builds these Aggregate Root
Query Name
Micro
Service
5. Handling Queries in the Process
Q Some commands are issued after the User interaction with Query Result
Event Listener Micro
Service
6. Listener listens for Domain & Integration Events
L Listeners plays the key role in Inter Micro Services communications
Aggregate
Factory
8. Factory
Factory Builds the Event
Sourced Aggregate Root based
on the Business Rules defined.
2. ESP is drawn inside 5 Vertical Swim Lanes.
1. Process Name & User interacting with the App
2. Actions by the user
3. Micro Service(s) involved
4. Events raised due to the command
5. Event Sourced Aggregate Root & Aggregate
Factory
3
Table OpenedOpen TableC DE
69
ESP : Customer’s Dinning Journey : 1–of–3
Actions Micro Service Events ES Aggregate2 3 4
List Food Menu Food
Menu
Q
Juice AddedAdd JuiceC DE
Soda AddedAdd SodaC DE
Appetizer 1 AddedAdd Appetizer 1C DE
Appetizer 2 AddedAdd Appetizer 2C DE
Soda RemovedRemove SodaC DE
Food 1 AddedAdd Food 1C DE
Order PlacedPlace OrderC IE
1. Dinning Order (This
will have all the Events
associated with the
Customers Dining
experience.)
2. Order (Will Contain
only the actual order)
Dining
The purpose of this example is to demonstrate the concept of ES / CQRS thru Event Storming principles.
Factory
Builds the
Aggregates
Process 1
Browse
Menu
Process 2
Order Food
Aggregate Root is
always derived from
the Event Store at the
time of the Query.
3
70
ESP : Customer’s Dinning Journey : 2–of–3
Actions Micro Service Events ES Aggregate2 3 4
Table ClosedClose TableC DE
Order PlacedOrder Listener DEL
Juice ServedServe JuiceC DE IE
Soda ServedServe SodaC DE IE
Appetizer 1 ServedServe Appetizer 1C DE IE
Juice ServedServing Listener DEL
Soda ServedServing Listener DEL
Appetizer 1 ServedServing Listener DEL
Food 1 ServedServing Listener DEL
Dining
Food PreparedPrepared FoodC DE
Food ServedServe FoodC DE IE
Kitchen
1. Order Served (This
Aggregate Root will
help track the Re-
Ordering the food
Raw materials)
3. Billable Order (This
will contain only the
Served Item)
Aggregate Root is
always derived from
the Event Store at the
time of the Query.
Factory
Builds the
Aggregates
Process 4
Serve Food
Process 3
Prepare Food
3
Payment StatusProcess PaymentC IE
71
ESP : Customer’s Dinning Journey : 3–of–3
Actions Micro Service Events ES Aggregate2 3 4
Payment ApprovedPayment Listener DEL
Bill PreparedPrepare BillC DE
Payment ProcessedProcess PaymentC DE IEOrder
1. Bill (This will
contain only the
Served Item)
Payment
2. Bill Payment (This
will contain the
Payment details)
Aggregate Root is always
derived from the Event
Store at the time of the
Query.
The purpose of this example is to demonstrate the concept of ES / CQRS thru Event Storming principles.
Factory
Builds the
Aggregates
Process 5
Make Payment
3
Use Case : Shopping Site – Event Sourcing / CQRS
72
Catalogue Shopping Cart Order Payment
• Search Products
• Add Products
• Update Products
Commands
• Add to Cart
• Remove Item
• Update Quantity
Customer
• Process Order
• Select Address
• Select Delivery Mode
Events
• Product Added
• Product Updated
• Product Discontinued
• Item Added
• Item Removed /
Discontinued
• Item Updated
• Order Initiated
• Address Selected
• Delivery Mode Selected
• Order Created
• Proceed for Payment
• Confirm Order for Payment
• Cancel Order
• Payment Initiated
• Order Cancelled
• Order Confirmed
• OTP Send
• Payment Approved
• Payment Declined
Commands are End-User interaction with the App and based on the commands (Actions) Events are created. These Events includes
both Domain Events and Integration Events. Event Sourced Aggregates will be derived using Domain Events. Each Micro Service will
have its own separate Database. Depends on the scalability requirement each of the Micro Service can be scaled separately. For
Example. Catalogue can be on a 50 node cluster compared to Customer Micro Service.
Microservices
• Customer
• Shop.. Cart
• Order
Customer Journey thru Shopping Process
The purpose of this example is to demonstrate the concept of ES / CQRS thru Event Storming principles.
3
2 ES Aggregate 4
3
Use Case : Movie Booking – Event Sourcing / CQRS
73
Order Payment
• Search Movies
• Add Movies
• Update Movies
Commands
• Select Movie
• Select Theatre / Show
• Select Tickets
• Process Order
• Select Food
• Food Removed
• Skip Food
• Process Order
Events
• Movie Added
• Movie Updated
• Movie Discontinued
• Movie Added
• Theatre / Show Added
• Tickets Added
• Order Initiated
• Popcorn Added
• Drinks Added
• Popcorn Removed
• Order Finalized
• Proceed for Payment
• Confirm Order for Payment
• Cancel Order
• Payment Initiated
• Order Cancelled
• Order Confirmed
• OTP Send
• Payment Approved
• Payment Declined
Movies Theatres Food
Microservices
Commands are End-User interaction with the App and based on the commands (Actions) Events are created. These Events includes both
Domain Events and Integration Events. Event Sourced Aggregates will be derived using Domain Events. Each Micro Service will have its
own separate Database. Depends on the scalability requirement each of the Micro Service can be scaled separately. For Example.
Theatre can be on a 50 node cluster compared to Food Micro Service.
• Theatre
• Show
• Order
Customer Journey thru booking Movie Ticket
The purpose of this example is to demonstrate the concept of ES / CQRS thru Event Storming principles.
3
2 ES Aggregate 4
3
Use Case : Movie Streaming – Event Sourcing / CQRS
74
Subscription Payment
• Search Movies
• Add Movies
• Update Movies
Commands
• Request Streaming
• Start Movie Streaming
• Pause Movie Streaming
• Validate Streaming
License
• Validate Download
License
Events
• Movie Added
• Movie Updated
• Movie Discontinued
• Streaming Requested
• Streaming Started
• Streaming Paused
• Streaming Done
• Streaming Request
Accepted
• Streaming Request
Denied
• Subscribe Monthly
• Subscribe Annually
• Monthly
Subscription Added
• Yearly Subscription
Added
• Payment Approved
• Payment Declined
Discovery
Microservices
Commands are End-User interaction with the App and based on the commands (Actions) Events are created. These Events includes both
Domain Events and Integration Events. Event Sourced Aggregates will be derived using Domain Events. Each Micro Service will have its
own separate Database. Depends on the scalability requirement each of the Micro Service can be scaled separately. For Example.
Theatre can be on a 50 node cluster compared to Food Micro Service.
• Stream List
• Favorite List
Customer Journey thru Streaming Movie / TV Show
The purpose of this example is to demonstrate the concept of ES / CQRS thru Event Storming principles.
LicenseStreaming
3
2 ES Aggregate 4
3
Summary – ESP : Event Sourcing Process map
75
Process1
Commands2
Projections5
ES Aggregate4
Events3
User Journey X
Bounded
Context
Bounded
Context
Bounded
Context
Front-End
Back-End
Database
Business
Capability 1
Front-End
Back-End
Database
Business
Capability 2
Front-End
Back-End
Database
Business
Capability 3
Vertically sliced Product Team
Ubiquitous
Language
Domain
Expert
Analyst
Developers
QA
Design
Docs
Test
Cases
Code
3
76
Bounded Context &
Hexagonal Architecture
• Ports & Adapters – Shopping Portal
77
Hexagonal Architecture
Ports & Adapters
The layer between the Adapter and
the Domain is identified as the Ports
layer. The Domain is inside the port,
adapters for external entities are on
the outside of the port.
The notion of a “port” invokes the
OS idea that any device that adheres
to a known protocol can be plugged
into a port. Similarly many adapters
may use the Ports.
Source : http://alistair.cockburn.us/Hexagonal+architecture
https://skillsmatter.com/skillscasts/5744-decoupling-from-asp-net-hexagonal-architectures-in-net
Services
for UI
Ports
File
system Database
Order Tracking
JPA Repository
Implementation
Adapters
OrderProcessing
Domain Service
(Business Rules)
Implementation
Domain
Models
Domain Layer
Order Data
Validation
OrderService
REST Service
Implementation
OrderProcessing
Interface
p
Order Tracking
Repository
Interface
p
A
A
External
Apps
A
A A
Others
A
A
OrderService
Interface
p
Web
Services
Data
Store
Use Case Boundary
Bounded Context
A
• Reduces Technical Debt
• Dependency Injection
• Auto Wiring
4
78
Specification Guidelines
• Approach to understanding
the Domain
• Discovering Bounded Context
Problem Space
79
Source: Patterns, Principles and Practices of DDD – Page xxxvi
5
How?
80
Focus on Core Complexity & Opportunity in
the Domain
Explore models in collaboration of Domain
Experts & Software Experts
Write software that expresses these
Models explicitly
Speak Ubiquitous Language within a
Bounded Context
Eric Evans – Explore DDD, Denver, 2017
5
Focus on
Clean
Boundaries
over
Perfect
Models
81Source: Patterns, Principles and Practices of DDD – Page 38
5
How?
Core
Domain
82
Identity the areas of the business which is
critical for the success of the business.
Why are these areas important?
Why can't we buy a solution rather than
building it?
What makes the system worth building it?
Look at the Core Domain as a Product instead of a Project
5
How?
Generic
Domains
83
An Email Sending Service
Notification Services like, SMS,
Google Notifications (for
Android), iPhone Notifications.
Reporting & Dashboard
functionalities
5
How?
Supporting
Domains
84
Supporting Domains are the domains
that helps the Core Domain.
In an E-Commerce application like
Amazon or Flipkart, product search
functionality is a supporting domain.
Even off the shelf application can be
used in a supporting domain, For Ex.
Ticketing system.
5
Solution Space
85Source: Patterns, Principles and Practices of DDD – Page xxxviI
5
Domain Vs. Domain Model
86Source: Patterns, Principles and Practices of DDD – Page 43
o Analysis Model or
Business Model is to
describe the Problem
space / Domain.
o The Domain Model
contains only what is
relevant to solve the
problem.
o Domain Model MUST be
free of technical
complexities.
5
Indicators
for
Discovering
Bounded
Context
87
Identify the Business Capabilities from
the User Activities / Stories / Use
Cases
Based on Activities: If an area within the
system contains a set of exclusive activities
then that’s an indicator for a Business
Capabilities.
Based on Trigger: Any area which gets
automatically triggered based on external
input and does some activities based on that
trigger. Ex. Spam Checker, Virus Checker in
mail attachments.
5
Start with? User Journey / Use Cases / Scenarios
88Source: Patterns, Principles and Practices of DDD – Chapter 2 – Page 16
5
Activities & User Journey / Ubiquitous Language
89
Process1
Commands2
Projections5
ES Aggregate4
Events3
User Journey X
Bounded
Context
Bounded
Context
Bounded
Context
Front-End
Back-End
Database
Business
Capability 1
Front-End
Back-End
Database
Business
Capability 2
Front-End
Back-End
Database
Business
Capability 3
Vertically sliced Product Team
Ubiquitous
Language
Domain
Expert
Analyst
Developers
QA
Design
Docs
Test
Cases
Code
5
List Core Activities
90
o List Code Activities for the
Primary Use Case
o Identify the Business Function
/ Capabilities of each of the
Activity
o Identify the User Role (Actor)
for this Activity,
o Ensure that the list of the
Activities complete the entire
Business Solution.
Activity Business
Function
Actor
1
2
3
4
5
6
7
8
9
10
5
User Journey: Shopping in E-Commerce Site
91
Catalogue Shopping Cart Order Payment
• Search Products
• Add Products
• Update Products
Commands
• Add to Cart
• Remove Item
• Update Quantity
Customer
• Process Order
• Select Address
• Select Delivery Mode
Events
• Product Added
• Product Updated
• Product Discontinued
• Item Added
• Item Removed /
Discontinued
• Item Updated
• Order Initiated
• Address Selected
• Delivery Mode Selected
• Order Created
• Proceed for Payment
• Confirm Order for Payment
• Cancel Order
• Payment Initiated
• Order Cancelled
• Order Confirmed
• OTP Send
• Payment Approved
• Payment Declined
Commands are End-User interaction with the App and based on the commands (Actions) Events are created. These Events includes
both Domain Events and Integration Events. Event Sourced Aggregates will be derived using Domain Events. Each Micro Service will
have its own separate Database. Depends on the scalability requirement each of the Micro Service can be scaled separately. For
Example. Catalogue can be on a 50 node cluster compared to Customer Micro Service.
Microservices
• Customer
• Shop.. Cart
• Order
Customer Journey thru Shopping Process
The purpose of this example is to demonstrate the concept of ES / CQRS thru Event Storming principles.
3
2 ES Aggregate 4
5
Cart OpenedOpen CartC DE
92
ESP : Customer’s Shopping Journey
Actions Micro Service Events ES Aggregate2 3 4
List Product Menu Product
Menu
Q
Book AddedAdd BookC DE
Pen AddedAdd PenC DE
Bag AddedAdd BagC DE
Book 2 AddedAdd Book 2C DE
Book 3 AddedAdd Book 3C DE
Book 2 RemovedRemove Book 2C DE
Order PlacedPlace OrderC IE
1. Shopping Cart (This
will have all the Events
associated with the
Customers Shopping
experience.)
2. Order (Will Contain
only the actual order)
Shopping
Cart
Factory
Builds the
Aggregates
Process 1
Browse
Catalogue
Process 2
Do Shopping
Aggregate Root is
always derived from
the Event Store at the
time of the Query.
5
93
Ubiquitous
Language
Vocabulary shared by
all involved parties
Used in all forms of spoken /
written communication
Ubiquitous
Language
Domain
Expert
Analyst Developers
QA
Design
Docs
Test Cases
Code
E-Commerce Context - Product:
Eg. In an E-Commerce Domain
the Product can have different
meanings in different context.
• Product Context in
Catalogue will have
product ID, image,
descriptions etc.
• Product Context in the
Inventory will keep track
of info like SKU, product
technical details from
storage perspective.
Use Case Scenarios – Ubiquitous Language & BDD
As an E-Commerce Owner
I want to know who my Customers are
So that I can serve them better with free
delivery / discounts
Role-Feature-Reason Matrix
BDD – Behavior Driven Development
Given Customer John Doe exists
When Customer orders items
Then
Assign Customer preference
based Item Category and
keep the count of items.
BDD Construct
5
User Case Scenarios – Behavior Driven Development
94
As an E-Commerce Owner
I want know my premium Customers
So that I can offer free delivery
Role-Feature-Reason Matrix
Given
Threshold for free delivery is set
at $70 and I am Customer who has
a basket totaling $50
When
I add an item to my basket costing
$21
Then I should be offered free delivery
BDD Construct
Customer
Offerings
Shopping
Cart
Order
Business
Capabilities
Bounded
Context
Given
Threshold for free delivery is set
at $70 and I am Customer who has
a basket totaling $60
When
I add an item to my basket costing
$7
Then
if I increase my total purchase
value by $3 then I will be offered
free Delivery.
BDD Construct
Scenario 1 Scenario 2
5
95
Implementation Guidelines
• Hexagonal Architecture
• Ports & Adapters – Shopping Portal
• RESTful Guidelines
96
Hexagonal Architecture
Ports & Adapters
The layer between the Adapter and
the Domain is identified as the Ports
layer. The Domain is inside the port,
adapters for external entities are on
the outside of the port.
The notion of a “port” invokes the
OS idea that any device that adheres
to a known protocol can be plugged
into a port. Similarly many adapters
may use the Ports.
Source : http://alistair.cockburn.us/Hexagonal+architecture
https://skillsmatter.com/skillscasts/5744-decoupling-from-asp-net-hexagonal-architectures-in-net
Services
for UI
Ports
File
system Database
Order Tracking
JPA Repository
Implementation
Adapters
OrderProcessing
Domain Service
(Business Rules)
Implementation
Domain
Models
Domain Layer
Order Data
Validation
OrderService
REST Service
Implementation
OrderProcessing
Interface
p
Order Tracking
Repository
Interface
p
A
A
External
Apps
A
A A
Others
A
A
OrderService
Interface
p
Web
Services
Data
Store
Use Case Boundary
Bounded Context
A
• Reduces Technical Debt
• Dependency Injection
• Auto Wiring
5
Shopping Portal Modules – Code Packaging
97
Auth Products Cart OrderCustomer
Domain Layer
• Models
• Repo
• Services
• Factories
Adapters
• Repo
• Services
• Web Services
Domain Layer
• Models
• Repo
• Services
• Factories
Adapters
• Repo
• Services
• Web Services
Domain Layer
• Models
• Repo
• Services
• Factories
Adapters
• Repo
• Services
• Web Services
Packaging Structure
Bounded Context
Implementation
(Repositories, Business Services, Web Services)
Domain Models
(Entities, Value Objects, DTOs)
(Repositories, Business Services, Web Services)
Entity Factories
Interfaces (Ports)
5
Shopping Portal
98
Order Bounded Context
Models
Value Object
• Currency
• Item Value
• Order Status
• Payment Type
• Record State
• Audit Log
Entity
• Order (Aggregate Root)
• Order Item
• Shipping Address
• Payment
DTO
• Order
• Order Item
• Shipping Address
• Payment
Domain Layer Adapters
• Order Repository
• Order Service
• Order Web Service
• Order Query Web Service
• Shipping Address Web Service
• Payment Web Service
Adapters Consists of Actual
Implementation of the Ports like
Database Access, Web Services
API etc.
Converters are used to convert
an Enum value to a proper
Integer value in the Database.
For Example Order Status
Complete is mapped to integer
value 100 in the database.
Services / Ports
• Order Repository
• Order Service
• Order Web Service
Utils
• Order Factory
• Order Status Converter
• Record State Converter
• Order Query Web Service
• Shipping Address Web Service
• Payment Web Service
5
Shopping Portal Design based on Hexagonal Architecture
99
5
RESTful Guidelines
100
1. Endpoints as nouns, NOT verbs
Ex. /catalogues
/orders
/catalogues/products
and NOT
/getProducts/
/updateProducts/
2. Use plurals
Ex. /catalogues/{catalogueId}
and NOT
/catalogue/{catalogueId}
3. Documenting
4. Paging
5. Use SSL
6. HTTP Methods
GET / POST / PUT / DELETE / OPTIONS / HEAD
7. HTTP Status Codes (Effective usage)
8. Versioning
Media Type Version
GET /account/5555 HTTP/1.1
Accept: application/vnd.catalogues.v1+json
URL path version
https://domain/v1/catalogues/products
5
RESTful Guidelines – Query Examples
101
Search All
Products
Search Products By
Catalogue ID
Search Products By
Catalogue ID & Product ID
5
RESTful Guidelines – Query Examples
102
Two different
implementation
of same query
5
RESTful Guidelines – Get & Create Example
103
URL Remains the same.
HTTP Methods Get / Post
Defines the action
5
RESTful Guidelines – Update & Delete Example
104
5
105
Design
Patterns are
solutions to
general
problems that
software
developers
faced during
software
development.
Design Patterns – Holy Grail of Developers
5
References
106
Domain Driven Design
16. Oct 27, 2012 What I have learned about DDD Since the book. By Eric Evans
17. Mar 19, 2013 Domain Driven Design By Eric Evans
18. May 16, 2015 Microsoft Ignite: Domain Driven Design for the Database Driven Mind
19. Jun 02, 2015 Applied DDD in Java EE 7 and Open Source World
20. Aug 23, 2016 Domain Driven Design the Good Parts By Jimmy Bogard
21. Sep 22, 2016 GOTO 2015 – DDD & REST Domain Driven API’s for the Web. By Oliver Gierke
22. Jan 24, 2017 Spring Developer – Developing Micro Services with Aggregates. By Chris Richardson
23. May 17. 2017 DEVOXX – The Art of Discovering Bounded Contexts. By Nick Tune
Event Sourcing and CQRS
23. Nov 13, 2014 GOTO 2014 – Event Sourcing. By Greg Young
24. Mar 22, 2016 Spring Developer – Building Micro Services with Event Sourcing and CQRS
25. Apr 15, 2016 YOW! Nights – Event Sourcing. By Martin Fowler
26. May 08, 2017 When Micro Services Meet Event Sourcing. By Vinicius Gomes
References
107
27. MSDN – Microsoft https://msdn.microsoft.com/en-us/library/dn568103.aspx
28. Martin Fowler : CQRS – http://martinfowler.com/bliki/CQRS.html
29. Udi Dahan : CQRS – http://www.udidahan.com/2009/12/09/clarified-cqrs/
30. Greg Young : CQRS - https://www.youtube.com/watch?v=JHGkaShoyNs
31. Bertrand Meyer – CQS - http://en.wikipedia.org/wiki/Bertrand_Meyer
32. CQS : http://en.wikipedia.org/wiki/Command–query_separation
33. CAP Theorem : http://en.wikipedia.org/wiki/CAP_theorem
34. CAP Theorem : http://www.julianbrowne.com/article/viewer/brewers-cap-theorem
35. CAP 12 years how the rules have changed
36. EBay Scalability Best Practices : http://www.infoq.com/articles/ebay-scalability-best-practices
37. Pat Helland (Amazon) : Life beyond distributed transactions
38. Stanford University: Rx https://www.youtube.com/watch?v=y9xudo3C1Cw
39. Princeton University: SAGAS (1987) Hector Garcia Molina / Kenneth Salem
40. Rx Observable : https://dzone.com/articles/using-rx-java-observable
References – Micro Services – Videos
41. Martin Fowler – Micro Services : https://www.youtube.com/watch?v=2yko4TbC8cI&feature=youtu.be&t=15m53s
42. GOTO 2016 – Microservices at NetFlix Scale: Principles, Tradeoffs & Lessons Learned. By R Meshenberg
43. Mastering Chaos – A NetFlix Guide to Microservices. By Josh Evans
44. GOTO 2015 – Challenges Implementing Micro Services By Fred George
45. GOTO 2016 – From Monolith to Microservices at Zalando. By Rodrigue Scaefer
46. GOTO 2015 – Microservices @ Spotify. By Kevin Goldsmith
47. Modelling Microservices @ Spotify : https://www.youtube.com/watch?v=7XDA044tl8k
48. GOTO 2015 – DDD & Microservices: At last, Some Boundaries By Eric Evans
49. GOTO 2016 – What I wish I had known before Scaling Uber to 1000 Services. By Matt Ranney
50. DDD Europe – Tackling Complexity in the Heart of Software By Eric Evans, April 11, 2016
51. AWS re:Invent 2016 – From Monolithic to Microservices: Evolving Architecture Patterns. By Emerson L, Gilt D. Chiles
52. AWS 2017 – An overview of designing Microservices based Applications on AWS. By Peter Dalbhanjan
53. GOTO Jun, 2017 – Effective Microservices in a Data Centric World. By Randy Shoup.
54. GOTO July, 2017 – The Seven (more) Deadly Sins of Microservices. By Daniel Bryant
55. Sept, 2017 – Airbnb, From Monolith to Microservices: How to scale your Architecture. By Melanie Cubula
56. GOTO Sept, 2017 – Rethinking Microservices with Stateful Streams. By Ben Stopford.
57. GOTO 2017 – Microservices without Servers. By Glynn Bird.
108
109
Araf Karsh Hamid : Co-Founder / CTO
araf.karsh@metamagic.in
USA: +1 (973) 969-2921
India: +91.999.545.8627
Skype / LinkedIn / Twitter / Slideshare : arafkarsh
http://www.slideshare.net/arafkarsh
https://www.linkedin.com/in/arafkarsh/
http://www.arafkarsh.com/
JPA 2.2 and JDBC
110
Java Type JDBC Type
java.time.LocalDate DATE
java.time.LocalTime TIME
java.time.LocalDateTime TIMESTAMP
java.time.OffsetTime TIME_WITH_TIMEZONE
java.time.OffsetDateTime TIMESTAMP_WITH_TIMEZONE

Weitere ähnliche Inhalte

Was ist angesagt?

Containers Docker Kind Kubernetes Istio
Containers Docker Kind Kubernetes IstioContainers Docker Kind Kubernetes Istio
Containers Docker Kind Kubernetes IstioAraf Karsh Hamid
 
Microservices Docker Kubernetes Istio Kanban DevOps SRE
Microservices Docker Kubernetes Istio Kanban DevOps SREMicroservices Docker Kubernetes Istio Kanban DevOps SRE
Microservices Docker Kubernetes Istio Kanban DevOps SREAraf Karsh Hamid
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven DesignRyan Riley
 
Domain Driven Design (DDD)
Domain Driven Design (DDD)Domain Driven Design (DDD)
Domain Driven Design (DDD)Tom Kocjan
 
Microservices Architecture - Cloud Native Apps
Microservices Architecture - Cloud Native AppsMicroservices Architecture - Cloud Native Apps
Microservices Architecture - Cloud Native AppsAraf Karsh Hamid
 
Microservices Architecture & Testing Strategies
Microservices Architecture & Testing StrategiesMicroservices Architecture & Testing Strategies
Microservices Architecture & Testing StrategiesAraf Karsh Hamid
 
Microservices Testing Strategies JUnit Cucumber Mockito Pact
Microservices Testing Strategies JUnit Cucumber Mockito PactMicroservices Testing Strategies JUnit Cucumber Mockito Pact
Microservices Testing Strategies JUnit Cucumber Mockito PactAraf Karsh Hamid
 
CQRS and Event Sourcing, An Alternative Architecture for DDD
CQRS and Event Sourcing, An Alternative Architecture for DDDCQRS and Event Sourcing, An Alternative Architecture for DDD
CQRS and Event Sourcing, An Alternative Architecture for DDDDennis Doomen
 
Micro services Architecture
Micro services ArchitectureMicro services Architecture
Micro services ArchitectureAraf Karsh Hamid
 
Design patterns for microservice architecture
Design patterns for microservice architectureDesign patterns for microservice architecture
Design patterns for microservice architectureThe Software House
 
Domain-Driven Design
Domain-Driven DesignDomain-Driven Design
Domain-Driven DesignAndriy Buday
 
Microservices, Containers, Kubernetes, Kafka, Kanban
Microservices, Containers, Kubernetes, Kafka, KanbanMicroservices, Containers, Kubernetes, Kafka, Kanban
Microservices, Containers, Kubernetes, Kafka, KanbanAraf Karsh Hamid
 
Implementing Domain Events with Kafka
Implementing Domain Events with KafkaImplementing Domain Events with Kafka
Implementing Domain Events with KafkaAndrei Rugina
 
Developing event-driven microservices with event sourcing and CQRS (svcc, sv...
Developing event-driven microservices with event sourcing and CQRS  (svcc, sv...Developing event-driven microservices with event sourcing and CQRS  (svcc, sv...
Developing event-driven microservices with event sourcing and CQRS (svcc, sv...Chris Richardson
 
Service Mesh - Observability
Service Mesh - ObservabilityService Mesh - Observability
Service Mesh - ObservabilityAraf Karsh Hamid
 
CQRS + Event Sourcing
CQRS + Event SourcingCQRS + Event Sourcing
CQRS + Event SourcingMike Bild
 

Was ist angesagt? (20)

Containers Docker Kind Kubernetes Istio
Containers Docker Kind Kubernetes IstioContainers Docker Kind Kubernetes Istio
Containers Docker Kind Kubernetes Istio
 
Microservices Docker Kubernetes Istio Kanban DevOps SRE
Microservices Docker Kubernetes Istio Kanban DevOps SREMicroservices Docker Kubernetes Istio Kanban DevOps SRE
Microservices Docker Kubernetes Istio Kanban DevOps SRE
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
 
Domain Driven Design (DDD)
Domain Driven Design (DDD)Domain Driven Design (DDD)
Domain Driven Design (DDD)
 
Microservices Architecture - Cloud Native Apps
Microservices Architecture - Cloud Native AppsMicroservices Architecture - Cloud Native Apps
Microservices Architecture - Cloud Native Apps
 
Microservices Architecture & Testing Strategies
Microservices Architecture & Testing StrategiesMicroservices Architecture & Testing Strategies
Microservices Architecture & Testing Strategies
 
Microservices Testing Strategies JUnit Cucumber Mockito Pact
Microservices Testing Strategies JUnit Cucumber Mockito PactMicroservices Testing Strategies JUnit Cucumber Mockito Pact
Microservices Testing Strategies JUnit Cucumber Mockito Pact
 
Introduction to DDD
Introduction to DDDIntroduction to DDD
Introduction to DDD
 
CQRS and Event Sourcing, An Alternative Architecture for DDD
CQRS and Event Sourcing, An Alternative Architecture for DDDCQRS and Event Sourcing, An Alternative Architecture for DDD
CQRS and Event Sourcing, An Alternative Architecture for DDD
 
Micro services Architecture
Micro services ArchitectureMicro services Architecture
Micro services Architecture
 
Design patterns for microservice architecture
Design patterns for microservice architectureDesign patterns for microservice architecture
Design patterns for microservice architecture
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
 
Domain-Driven Design
Domain-Driven DesignDomain-Driven Design
Domain-Driven Design
 
Microservices, Containers, Kubernetes, Kafka, Kanban
Microservices, Containers, Kubernetes, Kafka, KanbanMicroservices, Containers, Kubernetes, Kafka, Kanban
Microservices, Containers, Kubernetes, Kafka, Kanban
 
Docker Kubernetes Istio
Docker Kubernetes IstioDocker Kubernetes Istio
Docker Kubernetes Istio
 
Implementing Domain Events with Kafka
Implementing Domain Events with KafkaImplementing Domain Events with Kafka
Implementing Domain Events with Kafka
 
Developing event-driven microservices with event sourcing and CQRS (svcc, sv...
Developing event-driven microservices with event sourcing and CQRS  (svcc, sv...Developing event-driven microservices with event sourcing and CQRS  (svcc, sv...
Developing event-driven microservices with event sourcing and CQRS (svcc, sv...
 
Service Mesh - Observability
Service Mesh - ObservabilityService Mesh - Observability
Service Mesh - Observability
 
CQRS + Event Sourcing
CQRS + Event SourcingCQRS + Event Sourcing
CQRS + Event Sourcing
 
Event Storming and Saga
Event Storming and SagaEvent Storming and Saga
Event Storming and Saga
 

Ähnlich wie Domain Driven Design

Modernizing the monolithic architecture to container based architecture apaco...
Modernizing the monolithic architecture to container based architecture apaco...Modernizing the monolithic architecture to container based architecture apaco...
Modernizing the monolithic architecture to container based architecture apaco...Vinay Kumar
 
Best Practices Building Cloud Scale Apps with Microservices
Best Practices Building Cloud Scale Apps with MicroservicesBest Practices Building Cloud Scale Apps with Microservices
Best Practices Building Cloud Scale Apps with MicroservicesJim (张建军) Zhang
 
Unlock your core business assets for the hybrid cloud with addi webinar dec...
Unlock your core business assets for the hybrid cloud with addi   webinar dec...Unlock your core business assets for the hybrid cloud with addi   webinar dec...
Unlock your core business assets for the hybrid cloud with addi webinar dec...Sherri Hanna
 
Tackling 8 Digital Challenges of the Agrochemical, Industrial & Specialty Che...
Tackling 8 Digital Challenges of the Agrochemical, Industrial & Specialty Che...Tackling 8 Digital Challenges of the Agrochemical, Industrial & Specialty Che...
Tackling 8 Digital Challenges of the Agrochemical, Industrial & Specialty Che...Building Blocks
 
Product in a nutshell
Product in a nutshellProduct in a nutshell
Product in a nutshellKerem Kocak
 
A Case for Outside-In Design
A Case for Outside-In DesignA Case for Outside-In Design
A Case for Outside-In DesignSandro Mancuso
 
Best salesforce development company
Best salesforce development company Best salesforce development company
Best salesforce development company Kloudrac Softwares
 
Domain Driven Design Introduction
Domain Driven Design IntroductionDomain Driven Design Introduction
Domain Driven Design Introductionwojtek_s
 
On demand or on premise
On demand or on premiseOn demand or on premise
On demand or on premisePankaj Pandey
 
Discussion About Microservices Architecture
Discussion About Microservices ArchitectureDiscussion About Microservices Architecture
Discussion About Microservices ArchitectureRalph Osmond Rimorin
 
Esouag r12 presentation
Esouag r12 presentationEsouag r12 presentation
Esouag r12 presentationIshtiaq Khan
 
Agile Data Warehouse Design for Big Data Presentation
Agile Data Warehouse Design for Big Data PresentationAgile Data Warehouse Design for Big Data Presentation
Agile Data Warehouse Design for Big Data PresentationVishal Kumar
 
ISVs & the Commercial Transition to the Cloud
ISVs & the Commercial Transition to the CloudISVs & the Commercial Transition to the Cloud
ISVs & the Commercial Transition to the CloudInishTech
 
ISVs & the Commercial Transition to the Cloud
ISVs & the Commercial Transition to the CloudISVs & the Commercial Transition to the Cloud
ISVs & the Commercial Transition to the CloudSoftwarePotential
 

Ähnlich wie Domain Driven Design (20)

Modernizing the monolithic architecture to container based architecture apaco...
Modernizing the monolithic architecture to container based architecture apaco...Modernizing the monolithic architecture to container based architecture apaco...
Modernizing the monolithic architecture to container based architecture apaco...
 
Best Practices Building Cloud Scale Apps with Microservices
Best Practices Building Cloud Scale Apps with MicroservicesBest Practices Building Cloud Scale Apps with Microservices
Best Practices Building Cloud Scale Apps with Microservices
 
Unlock your core business assets for the hybrid cloud with addi webinar dec...
Unlock your core business assets for the hybrid cloud with addi   webinar dec...Unlock your core business assets for the hybrid cloud with addi   webinar dec...
Unlock your core business assets for the hybrid cloud with addi webinar dec...
 
Resume
ResumeResume
Resume
 
Tackling 8 Digital Challenges of the Agrochemical, Industrial & Specialty Che...
Tackling 8 Digital Challenges of the Agrochemical, Industrial & Specialty Che...Tackling 8 Digital Challenges of the Agrochemical, Industrial & Specialty Che...
Tackling 8 Digital Challenges of the Agrochemical, Industrial & Specialty Che...
 
Product in a nutshell
Product in a nutshellProduct in a nutshell
Product in a nutshell
 
COMPOSABLE COMPANY.pptx
COMPOSABLE COMPANY.pptxCOMPOSABLE COMPANY.pptx
COMPOSABLE COMPANY.pptx
 
Sathya-Resume
Sathya-ResumeSathya-Resume
Sathya-Resume
 
Quick App Flow
Quick App FlowQuick App Flow
Quick App Flow
 
Microservices Decomposition Patterns.v1.0.20191009
Microservices Decomposition Patterns.v1.0.20191009Microservices Decomposition Patterns.v1.0.20191009
Microservices Decomposition Patterns.v1.0.20191009
 
A Case for Outside-In Design
A Case for Outside-In DesignA Case for Outside-In Design
A Case for Outside-In Design
 
Microservices Decomposition Patterns
Microservices Decomposition PatternsMicroservices Decomposition Patterns
Microservices Decomposition Patterns
 
Best salesforce development company
Best salesforce development company Best salesforce development company
Best salesforce development company
 
Domain Driven Design Introduction
Domain Driven Design IntroductionDomain Driven Design Introduction
Domain Driven Design Introduction
 
On demand or on premise
On demand or on premiseOn demand or on premise
On demand or on premise
 
Discussion About Microservices Architecture
Discussion About Microservices ArchitectureDiscussion About Microservices Architecture
Discussion About Microservices Architecture
 
Esouag r12 presentation
Esouag r12 presentationEsouag r12 presentation
Esouag r12 presentation
 
Agile Data Warehouse Design for Big Data Presentation
Agile Data Warehouse Design for Big Data PresentationAgile Data Warehouse Design for Big Data Presentation
Agile Data Warehouse Design for Big Data Presentation
 
ISVs & the Commercial Transition to the Cloud
ISVs & the Commercial Transition to the CloudISVs & the Commercial Transition to the Cloud
ISVs & the Commercial Transition to the Cloud
 
ISVs & the Commercial Transition to the Cloud
ISVs & the Commercial Transition to the CloudISVs & the Commercial Transition to the Cloud
ISVs & the Commercial Transition to the Cloud
 

Mehr von Araf Karsh Hamid

Microservices, DevOps & SRE
Microservices, DevOps & SREMicroservices, DevOps & SRE
Microservices, DevOps & SREAraf Karsh Hamid
 
CI-CD Jenkins, GitHub Actions, Tekton
CI-CD Jenkins, GitHub Actions, Tekton CI-CD Jenkins, GitHub Actions, Tekton
CI-CD Jenkins, GitHub Actions, Tekton Araf Karsh Hamid
 
Cloud Architecture - Multi Cloud, Edge, On-Premise
Cloud Architecture - Multi Cloud, Edge, On-PremiseCloud Architecture - Multi Cloud, Edge, On-Premise
Cloud Architecture - Multi Cloud, Edge, On-PremiseAraf Karsh Hamid
 
Microservices Architecture, Monolith Migration Patterns
Microservices Architecture, Monolith Migration PatternsMicroservices Architecture, Monolith Migration Patterns
Microservices Architecture, Monolith Migration PatternsAraf Karsh Hamid
 
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
 
Apache Flink, AWS Kinesis, Analytics
Apache Flink, AWS Kinesis, Analytics Apache Flink, AWS Kinesis, Analytics
Apache Flink, AWS Kinesis, Analytics Araf Karsh Hamid
 
Blockchain HyperLedger Fabric Internals - Clavent
Blockchain HyperLedger Fabric Internals - ClaventBlockchain HyperLedger Fabric Internals - Clavent
Blockchain HyperLedger Fabric Internals - ClaventAraf Karsh Hamid
 
Blockchain Intro to Hyperledger Fabric
Blockchain Intro to Hyperledger Fabric Blockchain Intro to Hyperledger Fabric
Blockchain Intro to Hyperledger Fabric Araf Karsh Hamid
 
Microservices Architecture & Testing Strategies
Microservices Architecture & Testing StrategiesMicroservices Architecture & Testing Strategies
Microservices Architecture & Testing StrategiesAraf Karsh Hamid
 
Microservices Part 4: Functional Reactive Programming
Microservices Part 4: Functional Reactive ProgrammingMicroservices Part 4: Functional Reactive Programming
Microservices Part 4: Functional Reactive ProgrammingAraf Karsh Hamid
 
Blockchain Hyper Ledger Fabric : Bangkok Conference
Blockchain Hyper Ledger Fabric : Bangkok ConferenceBlockchain Hyper Ledger Fabric : Bangkok Conference
Blockchain Hyper Ledger Fabric : Bangkok ConferenceAraf Karsh Hamid
 
Blockchain - HyperLedger Fabric
Blockchain - HyperLedger FabricBlockchain - HyperLedger Fabric
Blockchain - HyperLedger FabricAraf Karsh Hamid
 

Mehr von Araf Karsh Hamid (15)

Elastic-Engineering
Elastic-EngineeringElastic-Engineering
Elastic-Engineering
 
Zero-Trust SASE DevSecOps
Zero-Trust SASE DevSecOpsZero-Trust SASE DevSecOps
Zero-Trust SASE DevSecOps
 
Microservices, DevOps & SRE
Microservices, DevOps & SREMicroservices, DevOps & SRE
Microservices, DevOps & SRE
 
CI-CD Jenkins, GitHub Actions, Tekton
CI-CD Jenkins, GitHub Actions, Tekton CI-CD Jenkins, GitHub Actions, Tekton
CI-CD Jenkins, GitHub Actions, Tekton
 
Cloud Architecture - Multi Cloud, Edge, On-Premise
Cloud Architecture - Multi Cloud, Edge, On-PremiseCloud Architecture - Multi Cloud, Edge, On-Premise
Cloud Architecture - Multi Cloud, Edge, On-Premise
 
Microservices Architecture, Monolith Migration Patterns
Microservices Architecture, Monolith Migration PatternsMicroservices Architecture, Monolith Migration Patterns
Microservices Architecture, Monolith Migration Patterns
 
Big Data Redis Mongodb Dynamodb Sharding
Big Data Redis Mongodb Dynamodb ShardingBig Data Redis Mongodb Dynamodb Sharding
Big Data Redis Mongodb Dynamodb Sharding
 
Apache Flink, AWS Kinesis, Analytics
Apache Flink, AWS Kinesis, Analytics Apache Flink, AWS Kinesis, Analytics
Apache Flink, AWS Kinesis, Analytics
 
Blockchain HyperLedger Fabric Internals - Clavent
Blockchain HyperLedger Fabric Internals - ClaventBlockchain HyperLedger Fabric Internals - Clavent
Blockchain HyperLedger Fabric Internals - Clavent
 
Blockchain Intro to Hyperledger Fabric
Blockchain Intro to Hyperledger Fabric Blockchain Intro to Hyperledger Fabric
Blockchain Intro to Hyperledger Fabric
 
Docker Kubernetes Istio
Docker Kubernetes IstioDocker Kubernetes Istio
Docker Kubernetes Istio
 
Microservices Architecture & Testing Strategies
Microservices Architecture & Testing StrategiesMicroservices Architecture & Testing Strategies
Microservices Architecture & Testing Strategies
 
Microservices Part 4: Functional Reactive Programming
Microservices Part 4: Functional Reactive ProgrammingMicroservices Part 4: Functional Reactive Programming
Microservices Part 4: Functional Reactive Programming
 
Blockchain Hyper Ledger Fabric : Bangkok Conference
Blockchain Hyper Ledger Fabric : Bangkok ConferenceBlockchain Hyper Ledger Fabric : Bangkok Conference
Blockchain Hyper Ledger Fabric : Bangkok Conference
 
Blockchain - HyperLedger Fabric
Blockchain - HyperLedger FabricBlockchain - HyperLedger Fabric
Blockchain - HyperLedger Fabric
 

Kürzlich hochgeladen

EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMKumar Satyam
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)Samir Dash
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAnitaRaj43
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 

Kürzlich hochgeladen (20)

EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 

Domain Driven Design

  • 1. ARAF KARSH HAMID Co-Founder / CTO MetaMagic Global Inc., NJ, USA @arafkarsh arafkarsh Domain Driven Design
  • 2. Agenda 2 • Hexagonal Architecture • Shopping Portal Example Hexagonal Architecture4 • Ubiquitous Language • Bounded Context • Context Maps Domain Driven Design – Strategic Design1 • Shopping Portal App • Specification Guidelines • Implementation Guidelines Case Study5 • Aggregate Roots • Entities / Value Objects • Factories • Repositories • Domain Events • Domain Service Domain Driven Design – Tactical Design2 • Object Modeling to Process Modeling • Capability Centric Design • Domain and Integration Events • Event Storming Concept and Diagrams • Event Storming Examples Event Storming3 • Monolithic to Microservices • Capability Centric Design Monolithic App0
  • 3. Monolithic > Microservices • FORRESTER RESEARCH • MODERNIZATION JOURNEY • ASSESS AND CLASSIFY YOUR APP PORTFOLIO • PLAN AND PRIORITIZE 3
  • 4. Conway’s Law 4 Any Organization that designs a system (defined broadly) will produce a design whose structure is a copy of the organization’s communication structure. 0
  • 5. * For IT Services : They can do one more project of same size with ZERO COST in Platform Licensing (Based on 20 developer pack USD $50K per month for 3 months License cost = $150K) 5 0
  • 6. Scale Cube and Micro Services 6 1. Y Axis Scaling – Functional Decomposition : Business Function as a Service 2. Z Axis Scaling – Database Partitioning : Avoid locks by Database Sharding 3. X Axis Scaling – Cloning of Individual Services for Specific Service Scalability 0
  • 7. Modernization Journey 7  Start new features as Microservices Incrementally establish the success early.  Expose Legacy On-Premise Apps API’s If legacy Apps cant be shifted to Cloud  Refactor Monolithic features to Microservices Breakdown and Deploy Feature by Feature  Containerize the Microservice Reduce costs, simplifies the operations and consistent environment between Dev, QA and Production  Monolith De-commission Plan Incrementally sunset the Monolith Velocity as you transform Increase your Delivery Velocity along the Journey High FuturePresent Low Inspired by a paper from IBM 0
  • 8. Assess and Classify your App Portfolio 8  Take inventory of your Apps Classify the Apps based on technology, complexity.  Align Apps to your Business Priorities Identify the Apps that are critical for Modernization.  Identify Business Modernization Requirements Create a Roadmap with faster go to market strategy  Understand the effort and Cost Evaluate all possible Modernization options Container Refactor Expose APIsLift & Shift BusinessValueCostComplexity Product Catalogue Product Review Inventory Shopping Cart Customer Profile Order Management Inspired by a paper from IBM 0
  • 9. Plan and Prioritize 9 Complexity Cost Value Score Rank Weightage 35% 25% 40% Customer Med 3 Med 3 Low 1 2.20 7 6 Product Reviews Med 3 High 5 Med 3 3.50 11 3 Product Catalogue Med 3 Med 3 High 5 4.80 11 1 Shopping Cart High 5 Med 3 Med 3 3.70 11 4 Order Very High 7 Med 3 High 5 5.20 15 2 Inventory Very High 7 High 5 Med 3 4.90 15 5  Prioritize Low Priority projects are good test cases but does not bring much business value.  Quick Wins Identify a feature / project which has good business value and low in complexity.  Project Duration Focus on shorter duration projects with high Business Value. Shopping Portal Features Prioritization Inspired by a paper from IBM 0
  • 10. Monolithic to Microservices Summary 10 1. Classify your Apps into Following areas 1. Lift and Shit 2. Containerize 3. Refactor 4. Expose API 2. Prioritize High Business Value Low Technical Complexity 3. Focus on Shorter Duration – From Specs to Operation 0
  • 11. CAPABILITY CENTRIC DESIGN • BUSINESS FUNCTIONS • BUSINESS PROCESS • TEAM STRUCTURE 11
  • 12. Business Solution & Business Process 12  Business Solution focuses the entire Journey of the User which can run across multiple Microservices.  Business Solution comprises a set of Business Processes.  A specific Microservice functionality will be focused on a Business Process / Concern  Business Process can be divided further into Business Functions Business Solution: Customer Dining Experience Order PaymentFood Menu KitchenDining Browse Menu Order Dinner Dinner Served Get Bill Make Payment 0
  • 13. Capability Centric Design 13 Vertically sliced Product Team Business Centric Development • Focus on Business Capabilities • Entire team is aligned towards Business Capability. • From Specs to Operations – The team handles the entire spectrum of Software development. • Every vertical will have it’s own Code Pipeline Front-End-Team Back-End-Team Database-Team In a typical Monolithic way the team is divided based on technology / skill set rather than business functions. This leads to not only bottlenecks but also lack of understanding of the Business Domain. QA / QC Team Front-End Back-End Database Business Capability 1 QA/QCTeam Front-End Back-End Database Business Capability 2 QA/QCTeam Front-End Back-End Database Business Capability 3 QA/QCTeam 0
  • 14. 14 From Project Based Activity Oriented To Product Based Outcome Oriented Source: Sriram Narayan– https://martinfowler.com/bliki/BusinessCapabilityCentric.html 0
  • 15. Capability Centric Design Summary 15 1. Business Solutions 2. Business Process 3. Business Capabilities 4. Business Driven Teams (From Specs to Ops) 5. Outcome Oriented instead of Activity Oriented. 0 Business Solution Business Process 1 Business Process 2 Business Process n Business Capability 1 Business Capability 2 Business Capability n
  • 16. 16 Domain Driven Design • Strategic Design • Tactical Design o Ubiquitous Language o Bounded Context o Context Map
  • 17. 17 Ubiquitous Language Vocabulary shared by all involved parties Used in all forms of spoken / written communication Ubiquitous Language Domain Expert Analyst Developers QA Design Docs Test Cases Code Restaurant Context – Food Item : Eg. Food Item (Navrathnakurma) can have different meaning or properties depends on the context. • In the Menu Context it’s a Veg Dish. • In the Kitchen Context it’s is recipe. • And in the Dining Context it will have more info related to user feed back etc. DDD: Ubiquitous Language: Strategic Design As an Restaurant Owner I want to know who my Customers are So that I can serve them better Role-Feature-Reason Matrix BDD – Behavior Driven Development Given Customer John Doe exists When Customer orders food Then Assign customer preferences as Veg or Non Veg customer BDD Construct
  • 18. Bounded Context – Strategic Design 18 1 • Bounded Context is a Specific Business Process / Concern. • Components / Modules inside the Bounded Context are context specific. • Multiple Bounded Contexts are linked using Context Mapping. • One Team assigned to a Bounded Context. • Each Bounded Context will have it’s own Source Code Repository. • When the Bounded Context is being developed as a key strategic initiative of your organization, it’s called the Core Domain. • Within a Bounded Context the team must have same language called Ubiquitous language for Spoken and for Design / Code Implementation.
  • 19. DDD: Bounded Context – Strategic Design 19 An App User’s Journey can run across multiple Bounded Context / Micro Services. Dinning Order Reservation Tables Recipes Raw Materials Frozen Semi Cooked Appetizer Veg Appetizer Non Veg Soft Drinks Main Course Non Veg Main Course Veg Hot Drinks Desserts Steward Chef Menu uses uses Dinning Order Reservation Tables Recipes Raw Materials Frozen Semi Cooked Appetizer Veg Appetizer Non Veg Soft Drinks Main Course Non Veg Main Course Veg Hot Drinks Desserts Steward Chef Menu uses uses UnderstandingBoundedContext(DDD)ofaRestaurantApp Dinning Context Kitchen Context Menu Context Source: Domain-Driven Design Reference by Eric Evans 1 Areas of the domain treated independently Discovered as you assess requirements and build language Bounded Context Bounded Context Bounded Context User Journey X
  • 20. 20 DDD : Understanding Bounded Context1 Source: Patterns, Principles and Practices of DDD – Page 124 This model shows multiple responsibilities of the shared Model – Product. This is a classic example of Big Ball of Mud.
  • 21. 21 DDD : Understanding Bounded Context1 Source: Patterns, Principles and Practices of DDD – Page 127 Each of this context will become a Microservice
  • 22. 22 DDD : Understanding Bounded Context Source: BoundedContext By Martin Fowler : http://martinfowler.com/bliki/BoundedContext.html • DDD deals with large models by dividing them into different Bounded Contexts and being explicit about their interrelationships. • Bounded Contexts have both unrelated concepts • Such as a support ticket only existing in a customer support context • But also share concepts such as products and customers. • Different contexts may have completely different models of common concepts (Customer & Product) with mechanisms to map between these polysemic concepts for integration. 1
  • 23. Customer Model in Different Bounded Context 23 Order Customer • Customer ID • Discount • Bonus Program Delivery Customer • Customer ID • Address • Preferred Delivery method • Packaging • Delivery Contact Billing Customer • Customer ID • Billing Address • Payment Type • Tax o Customer Model has different attributes in different contexts. So it avoids storing all the customer info in one place and then sharing that across multiple Bounded Contexts (Microservices). o If you want to change Customer details related to Tax then only Billing Bounded Context (Microservice) needs to be updated. 1
  • 24. 24 DDD : Understanding Bounded Context1 Source: Patterns, Principles and Practices of DDD – Page 132 Each of this Bounded Context will become a Microservice Communication across Bounded Context Source: Patterns, Principles and Practices of DDD – Page 203
  • 25. 25 DDD : Understanding Bounded Context1 Source: Patterns, Principles and Practices of DDD – Page 157 Microservice is a Bounded Context
  • 26. DDD : Context Map 26 Source: Domain-Driven Design Reference by Eric Evans 1 (C) COPYRIGHT METAMAGIC GLOBAL INC., NEW JERSEY, USA
  • 27. DDD : Understanding Context Map 1. A context map provides Global View of the system that UML or architecture diagrams completely miss, helping us to focus on choices that are really viable in your scenario without wasting money. 2. Each Bounded Context fits within the Context Map to show how they should communicate amongst each other and how data should be shared. 27 Up Stream (u) – Down Stream (d) The upstream team may succeed independently of the fate of the downstream team. Mutually Dependent Success depends on the success of both the teams. Free In which success or failure of the development work in other contexts has little affect on delivery. 1
  • 28. DDD: Context Map 28 Term Definition Action Partnership When teams in two context will succeed or fail together, a cooperative relationship often emerges. Forge Partnerships Shared Kernel Sharing a part of the Mode and associated code is very intimate interdependency, which can leverage design work or undermine it. Keep the Kernel Small. Customer / Supplier When two teams are in upstream – downstream relationship, where the upstream team may succeed independently of the fate of the downstream team, the needs of the downstream come to be addressed in a variety of ways with wide range of consequences. Downstream priorities factor into upstream planning. Conformist Upstream has no motivation in this partnership to keep the promise. Altruism may motivate Upstream developers to give promises they cant keep. Share just enough info with upstream to keep their motivation. Anti Corruption Layer When the translation between two bounded context becomes more complex, then the translation layer takes on a more defensive tone. (down stream) creates a layer in sync own model and matching (up stream) functionality. 1
  • 29. DDD: Context Map 29 Term Definition Action Open Host Service When a subsystem has to be integrated with many others, customizing a translator for each can bog down the team. There is more and more to maintain, and more and more to worry about when changes are made. Use a one of translator to augment the Protocol to share info (REST) Published Language Translation between the models of two bounded contexts requires a common language. Published Language is often combined with Open Host Service. Use a well documented shared language (JSON) Separate Ways If two sets of functionality have no significant relationship, they can be completely cut loose from each other. Integration is always expensive and sometimes the benefit is small. Bounded context with no connection to others. Big Ball of Mud As we survey existing systems, we find that, in fact, there are parts of systems, often large ones, where models are mixed and boundaries are inconsistent. Designate the mess as a Big Ball of Mud. 1
  • 30. Context Map – Coordination Efforts 30 Shared Bounded Context Shared Kernel Customer / Supplier Published Language Open Host Service Anticorruption Layer Conformist Separate Ways Coordination Effort 1
  • 31. DDD: Strategic Design Patterns 31 Pattern Description Page 1 Bounded Context They are NOT Modules A Bounded Context delimits the applicability of a particular model so that the team members have a clear and shared understanding of what has to be consistent and how it relates to other Contexts. Contexts can be created from (but not limited to) the following: • how teams are organized • the structure and layout of the code base • usage within a specific part of the domain 335 2 Context Map Context mapping is a design process where the contact points and translations between bounded contexts are explicitly mapped out. Focus on mapping the existing landscape, and deal with the actual transformations later. 1. Shared Kernel 2. Customer / Supplier 3. Conformist 4. Anti Corruption Layer 5. Separate Ways 3 Specification Pattern Use the specification pattern when there is a need to model rules, validation and selection criteria. The specification implementations test whether an object satisfies all the rules of the specification. 4 Strategy Pattern The strategy pattern, also known as the Policy Pattern is used to make algorithms interchangeable. In this pattern, the varying 'part' is factored out. 5 Composite Pattern This is a direct application of the GoF pattern within the domain being modeled. The important point to remember is that the client code should only deal with the abstract type representing the composite element. Page Number from Domain Driven Design – Published in 2015 1
  • 32. Common Problems 32 1 1. Trying to make a perfect Boundary for the Context. 2. Overemphasizing the importance of Tactical Design Patterns 3. Using the same architecture for all Bounded Contexts 4. Neglecting the Strategic Design Patterns 5. Focusing on Code rather than the principles of DDD
  • 33. 33 Domain Driven Design • Strategic Design • Tactical Design o Entity o Value Object o Aggregate Root o Factory o Repository o Domain Service o Domain Events
  • 34. Domain Driven Design 34 Source: Domain-Driven Design Reference by Eric Evans 2
  • 35. Layered Architecture 35 2 • Explicit Domain Models – Isolate your models from UI, Business Logic. • Domain Objects – Free of the Responsibility of displaying themselves or storing themselves or managing App Tasks. • Zero Dependency on Infrastructure, UI and Persistent Layers. • Use Dependency Injection for Loosely Coupled Objects. • All the Code for Domain Model in a Single Layer. • Domain Model should be Rich enough to represent Business Knowledge. Source: DDD Reference by Chris Evans Page 17
  • 36. Entity 36 2 Entities are Domain Concepts with Identity and Continuity and can be stored in a database. Identity Examples of an Entity • Order ID in Order Entity • Social Security Number in Person Entity • Shipping ID in Shipping Address Entity • Order (Aggregate Root) • Order Item • Shipping Address • Payment
  • 37. Value Objects 37 2 Value Object • Currency • Item Value • Order Status • Payment Type • Record State • Audit Log Value object represent a specific business concept related that Bounded Context in that Sub- domain. Value objects doesn’t have any specific identity and it’s not stored in the database. It exists as part of an Entity.
  • 38. Understanding Aggregate Root 38 Order Customer Shipping Address Aggregate Root Line Item Line Item Line Item * Payment Strategy Credit Card Cash Bank Transfer Source: Martin Fowler : Aggregate Root • An aggregate will have one of its component objects be the aggregate root. Any references from outside the aggregate should only go to the aggregate root. The root can thus ensure the integrity of the aggregate as a whole. • Aggregates are the basic element of transfer of data storage - you request to load or save whole aggregates. Transactions should not cross aggregate boundaries. • Aggregates are sometimes confused with collection classes (lists, maps, etc.). • Aggregates are domain concepts (order, clinic visit, playlist), while collections are generic. An aggregate will often contain multiple collections, together with simple fields. 125 Domain Driven Design (C) COPYRIGHT METAMAGIC GLOBAL INC., NEW JERSEY, USA 2
  • 39. Designing and Fine Tuning Aggregate Root 39 Source : Effective Aggregate Design Part 1/2/3 : Vaughn Vernon http://dddcommunity.org/wp-content/uploads/files/pdf_articles/Vernon_2011_1.pdf Aggregate Root - #1 Aggregate Root - #2 Super Dense Single Aggregate Root Results in Transaction concurrency issues. Super Dense Aggregate Root is split into 4 different smaller Aggregate Root in the 2nd Iteration. Working on different design models helps the developers to come up with best possible design. (C) COPYRIGHT METAMAGIC GLOBAL INC., NEW JERSEY, USA 2
  • 40. 40 Rules for Building Aggregate Roots 1. Protect True Invariants in Consistency Boundaries. This rule has the added implication that you should modify just one Aggregate instance in a single transaction. In other words, when you are designing an Aggregate composition, plan on that representing a transaction boundary. 2. Design Small Aggregates. The smallest Aggregate you can design is one with a single Entity, which will serve as the Aggregate Root. 3. Reference Other Aggregates Only By Identity. 4. Use Eventual Consistency Outside the Consistency Boundary. This means that ONLY ONE Aggregate instance will be required to be updated in a single transaction. All other Aggregate instances that must be updated as a result of any one Aggregate instance update can be updated within some time frame (using a Domain Event). The business should determine the allowable time delay. 5. Build Unidirectional Relationship from the Aggregate Root. 2
  • 41. Domain Services 41 2 Domain Services focuses bringing the Behavior to your Domain involving Entities and Value Objects. It focuses on a Single Responsibility. Implementation of the Domain Service resides in the service layer and not in the Domain Layer. Domain Layer • Models • Repo • Services • Factories Adapters • Repo • Services • Web Services
  • 42. Domain Events & Integration Events 42 1. Domain Events represent something happened in a specific Domain. 2. Domain Events should be used to propagate STATE changes across Multiple Aggregates within the Bounded Context. 3. The purpose of Integration Events is to propagate committed transactions and updates to additional subsystems, whether they are other microservices, Bounded Contexts or even external applications. Source: Domain Events : Design and Implementation – Microsoft Docs – May 26, 2017 Domain Data Behavior Order (Aggregate Root) Data Behavior Address (Value Object) Data Behavior OrderItem (Child) 1 n 1 1 Order Created Domain Event Domain Layer Enforce consistency with other Aggregates Event Handler 1 Event Handler n Create and Publish Integration Event to Event Bus. Example: Order Placed Integration Event can be subscribed by Inventory system to update the Inventory details. Event Handler 2 2
  • 43. Communication Synchronous – RPC 43 2 Source: Patterns, Principles and Practices of DDD – Page 212
  • 44. Communication Async – Event Based 44 2 Source: Patterns, Principles and Practices of DDD – Page 217
  • 45. Reactive Programming Comparison : Iterable / Streams / Observable 45 First Class Visitor (Consumer) Serial Operations Parallel Streams (10x Speed) Still On Next, On Complete and On Error are Serial Operations Completely Asynchronous Operations Java 8 – Blocking CallJava 6 – Blocking Call Rx Java - Freedom 2
  • 46. Reactive Programming RxJava Operator : Filter / Sort / FlatMap 46 Objective: toSortedList() returns an Observable with a single List containing Fruits. Using FlatMap to Transform Observable <List> to Observable <Fruit> Rx Example 2 2
  • 47. Data Transfer Object vs. Value Object 47 Data Transfer Object Value Object A DTO is just a data container which is used to transport data between layers and tiers. A Value Object represents itself a fix set of data and is similar to a Java enum. It mainly contains of attributes and it’s a serializable object. A Value Object doesn't have any identity, it is entirely identified by its value and is immutable. DTOs are anemic in general and do not contain any business logic. A real world example would be Color.RED, Color.BLUE, Currency.USD Patterns of Enterprise Application Architecture : Martin Fowler http://martinfowler.com/books/eaa.html A small simple object, like money or a date range, whose equality isn’t based on identity. 486 P of EAA Java EE 7 Retired the DTO In Java EE the RS spec became the de-facto standard for remoting, so the implementation of serializable interface is no more required. To transfer data between tiers in Java EE 7 you get the following for FREE! 1. JAXB : Offer JSON / XML serialization for Free. 2. Java API for JSON Processing – Directly serialize part of the Objects into JSON 2
  • 48. DTO – Data Transfer Object Security Considerations Data obtained from untrusted sources, such as user input from a Web page, should be cleansed and validated before being placed into a DTO. Doing so enables you to consider the data in the DTO relatively safe, which simplifies future interactions with the DTO. 48 The Problem Assembler Pattern An object that carries data between processes in order to reduce the number of method calls. Benefits 1. Reduced Number of Calls 2. Improved Performance 3. Hidden Internals 4. Discovery of Business objects Liabilities 1. Class Explosion 2. Additional Computation 3. Additional Coding Effort https://msdn.microsoft.com/en-us/library/ms978717.aspx Problem: How do you preserve the simple semantics of a procedure call interface without being subject to the latency issues inherent in remote communication? The Solution 401 P of EAA 2
  • 49. DTO – Data Transfer Object 49 An object that carries data between processes in order to reduce the number of method calls. The most misused pattern in the Java Enterprise community is the DTO. DTO was clearly defined as a solution for a distribution problem. DTO was meant to be a coarse-grained data container which efficiently transports data between processes (tiers). On the other hand considering a dedicated DTO layer as an investment, rarely pays off and often lead to over engineered bloated architecture. Real World Java EE Patterns Adam Bien http://realworldpatterns.com Don't underestimate the cost of [using DTOs].... It's significant, and it's painful - perhaps second only to the cost and pain of object- relational mapping. Another argument I've heard is using them in case you want to distribute later. This kind of speculative distribution boundary is what I rail against. Adding remote boundaries adds complexity. One case where it is useful to use something like a DTO is when you have a significant mismatch between the model in your presentation layer and the underlying domain model. In this case it makes sense to make presentation specific facade/gateway that maps from the domain model and presents an interface that's convenient for the presentation. Patterns of Enterprise Application Architecture : Martin Fowler http://martinfowler.com/books/eaa.html 401 P of EAA 2
  • 50. 50 Other subsystemAnti-corruption layer 365 Domain Driven Design Your subsystem 2 Anti Corruption Layer – ACL
  • 51. Repository Pattern Objectives Use the Repository pattern to achieve one or more of the following objectives: • You want to maximize the amount of code that can be tested with automation and to isolate the data layer to support unit testing. • You access the data source from many locations and want to apply centrally managed, consistent access rules and logic. • You want to implement and centralize a caching strategy for the data source. • You want to improve the code's maintainability and readability by separating business logic from data or service access logic. • You want to use business entities that are strongly typed so that you can identify problems at compile time instead of at run time. • You want to associate a behavior with the related data. For example, you want to calculate fields or enforce complex relationships or business rules between the data elements within an entity. • You want to apply a domain model to simplify complex business logic. 51 Repository Pattern Source: Martin Fowler : http://martinfowler.com/eaaCatalog/repository.html | Microsoft : https://msdn.microsoft.com/en-us/library/ff649690.aspx Mediates between the domain and data mapping layers using a collection- like interface for accessing domain objects. 322 P of EAA Conceptually, a Repository encapsulates the set of objects persisted in a data store and the operations performed over them, providing a more object-oriented view of the persistence layer. Repository also supports the objective of achieving a clean separation and one-way dependency between the domain and data mapping layers. 2
  • 52. Anemic Domain Model : Anti Pattern • There are objects, many named after the nouns in the domain space, and these objects are connected with the rich relationships and structure that true domain models have. • The catch comes when you look at the behavior, and you realize that there is hardly any behavior on these objects, making them little more than bags of getters and setters. • The fundamental horror of this anti-pattern is that it's so contrary to the basic idea of object-oriented design; which is to combine data and process together. • The anemic domain model is really just a procedural style design, exactly the kind of thing that object bigots like me (and Eric) have been fighting since our early days in Smalltalk. 52 Source: Anemic Domain Model By Martin Fowler : http://martinfowler.com/bliki/AnemicDomainModel.html • lockUser() • unlockUser() • addAddress(String address) • removeAddress(String address) 2
  • 53. Procedural Design Vs. Domain Driven Design 53 1. Anemic Entity Structure 2. Massive IF Statements 3. Entire Logic resides in Service Layer 4. Type Dependent calculations are done based on conditional checks in Service Layer 4 1 23 Source: http://www.javaworld.com/article/2078042/java-app-dev/domain-driven-design-with-java-ee-6.html Domain Driven Design with Java EE 6 By Adam Bien | Javaworld 2
  • 54. Polymorphic Business Logic inside a Domain object 54 Domain Driven Design with Java EE 6 By Adam Bien | Javaworld Computation of the total cost realized inside a rich Persistent Domain Object (PDO) and not inside a service. This simplifies creating very complex business rules. Source: http://www.javaworld.com/article/2078042/java-app-dev/domain-driven-design-with-java-ee-6.html 2
  • 55. Type Specific Computation in a Sub Class 55 Source: http://www.javaworld.com/article/2078042/java-app-dev/domain-driven-design-with-java-ee-6.html We can change the computation of the shipping cost of a Bulky Item without touching the remaining classes. Its easy to introduce a new Sub Class without affecting the computation of the total cost in the Load Class. Domain Driven Design with Java EE 6 By Adam Bien | Javaworld of 2
  • 56. Object Construction : Procedural Way Vs. Builder Pattern 56 Procedural Way Builder Pattern Source: http://www.javaworld.com/article/2078042/java-app-dev/domain-driven-design-with-java-ee-6.html Domain Driven Design with Java EE 6 By Adam Bien | Javaworld 2
  • 57. DDD: Tactical Design Patterns 57 Pattern Description Page 6 Entity An object defined Primarily by its identity is called an Entity 91 - Value Object (Already referred in P of EAA) Many Objects have no conceptual Identity. These objects describe the characteristic of a thing. 97 7 Aggregate Aggregate is a cluster of domain objects that can be treated as a Single Unit. Example Order and Order Item. 125 Aggregate Root An Aggregate will have one of its component object be the Aggregate Root. 127 - Repositories (Already referred in P of EAA) A Repository represents all objects of a certain type as a conceptual set. It acts like a collection, except with more elaborate querying capabilities. Objects of appropriate type are added and removed, and the machinery behind the Repository inserts them or deletes them from the database. This definition gathers a cohesive set of responsibilities for providing access to the roots of Aggregates from early life cycle through the end. 147 8 Factory / Builder Pattern When creation of an Object, or an entire Aggregate, becomes complicated or reveals too much of the internal structure, Factories provides encapsulation. 136 Page Number from Domain Driven Design – Published in 2015 2
  • 58. DDD: Tactical Design Patterns 58 Pattern Description Page 9 Factory / Builder Pattern When creation of an Object, or an entire Aggregate, becomes complicated or reveals too much of the internal structure, Factories provides encapsulation. 136 10 Domain Service A Service tends to be named of an Activity rather than an Entity. 1. The Operation relates to a domain concept that is not a natural part of an Entity. 2. The interface is defined in terms of other elements of the Domain Model 3. The operation is stateless 104 11 Anti – Corruption Layer (External Integration) Creating an isolating layer to provide clients with functionality in terms of their own Domain Model. The layer talks to the other system through its existing interface, requiring little or no modification to the other system. Internally the Layer translates in both directions as necessary between the two models. 365 12 Domain Events A Domain Event is a full-fledged part of the Domain Model, a representation of of something that happened in the Domain. Explicit events that the domain experts wants to track and notified of or which are associated with the state changes in other Domain Models. Page Number from Domain Driven Design – Published in 2015 2
  • 59. Shopping Portal 59 Order ContextModels Value Object • Currency • Item Value • Order Status • Payment Type • Record State • Audit Log Entity • Order (Aggregate Root) • Order Item • Shipping Address • Payment DTO • Order • Order Item • Shipping Address • Payment Domain Layer Adapters • Order Repository • Order Service • Order Web Service • Order Query Web Service • Shipping Address Web Service • Payment Web Service Adapters Consists of Actual Implementation of the Ports like Database Access, Web Services API etc. Converters are used to convert an Enum value to a proper Integer value in the Database. For Example Order Status Complete is mapped to integer value 100 in the database. Services / Ports • Order Repository • Order Service • Order Web Service Utils • Order Factory • Order Status Converter • Record State Converter • Order Query Web Service • Shipping Address Web Service • Payment Web Service 2
  • 60. DDD – Summary 60 1. Ubiquitous Language 2. Bounded Context 3. Context Map 4. Entity 5. Value Object 6. Aggregate Root 7. Factory 8. Repository Pattern 9. Domain Service 10. Domain Events 11. Data Transfer Object More on Event Storming 2
  • 61. 61 Event Storming • Object Modeling to Process Modeling • Domain Events for State Change • Event Storming Process
  • 62. Mind Shift : From Object Modeling to Process Modeling 62 3 Developers with Strong Object Modeling experience will have trouble making Events a first class citizen. • How do I start Event Sourcing? • Where do I Start on Event Sourcing / CQRS? The Key is: 1. App User’s Journey 2. Business Process 3. Ubiquitous Language – DDD 4. Capability Centric Design 5. Outcome Oriented The Best tool to define your process and its tasks. How do you define your End User’s Journey & Business Process? • Think It • Build It • Run IT
  • 63. Business Solution & Business Process 63  Business Solution focuses the entire Journey of the User which can run across multiple Micro Services.  Business Solution comprises a set of Business Processes.  Business Process focuses on a specific Micro Service and its functionality. Business Solution: Customer Dining Experience Order PaymentFood Menu KitchenDining Browse Menu Order Dinner Dinner Served Get Bill Make Payment 3
  • 64. Domain Events & Integration Events 64 1. Domain Events represent something happened in a specific Domain. 2. Domain Events should be used to propagate STATE changes across Multiple Aggregates within the Bounded Context. 3. The purpose of Integration Events is to propagate committed transactions and updates to additional subsystems, whether they are other microservices, Bounded Contexts or even external applications. Source: Domain Events : Design and Implementation – Microsoft Docs – May 26, 2017 Domain Data Behavior Order (Aggregate Root) Data Behavior Address (Value Object) Data Behavior OrderItem (Child) 1 n 1 1 Order Created Domain Event Domain Layer Enforce consistency with other Aggregates Event Handler 1 Event Handler n Create and Publish Integration Event to Event Bus. Example: Order Placed Integration Event can be subscribed by Inventory system to update the Inventory details. Event Handler 2 3
  • 65. 65 Process • Define your Business Processes. Eg. Various aspects of Order Processing in an E-Commerce Site, Movie Ticket Booking, Patient visit in Hospital.1 Commands • Define the Commands (End-User interaction with your App) to execute the Process. Eg. Add Item to Cart is a Command.2 Event Sourced Aggregate • Current state of the Aggregate is always derived from the Event Store. Eg. Shopping Cart, Order etc. This will be part of the Rich Domain Model (Bounded Context) of the Micro Service.4 Projections • Projections focuses on the View perspective of the Application. As the Read & Write are different Models, you can have different Projections based on your View perspective. 5 Write Data Read Data Events • Commands generates the Events to be stored in Event Store. Eg. Item Added Event (in the Shopping Cart).3 Event Storming – Concept3
  • 66. 66 Event Sourcing Intro Standard CRUD Operations – Customer Profile – Aggregate Root Profile Created Title Updated New Address added Derived Notes Removed Time T1 T2 T4T3 Event Sourcing and Derived Aggregate Root Commands 1. Create Profile 2. Update Title 3. Add Address 4. Delete Notes 2 Events 1. Profile Created Event 2. Title Updated Event 3. Address Added Event 4. Notes Deleted Event 3 Current State of the Customer Profile 4 Event store Single Source of Truth Greg Young 3
  • 67. Event Storming : Restaurant Dining Example – Customer Journey 67 Order Payment • Add Drinks • Add Food • Update Food Commands • Open Table • Add Juice • Add Soda • Add Appetizer 1 • Add Appetizer 2 • Serve Drinks • Prepare Food • Serve Food Events • Drinks Added • Food Added • Food Updated • Food Discontinued • Table Opened • Juice Added • Soda Added • Appetizer 1 Added • Appetizer 2 Added • Juice Served • Soda Served • Appetizer Served • Food Prepared • Food Served • Prepare Bill • Process Payment • Bill Prepared • Payment Processed • Payment Approved • Payment Declined • Cash Paid When people arrive at the Restaurant and take a table, a Table is opened. They may then order drinks and food. Drinks are served immediately by the table staff, however food must be cooked by a chef. Once the chef prepared the food it can then be served. Table is closed when the bill is prepared. Microservices • Dinning Order • Billable Order Customer Journey thru Dinning Processes Processes Food Menu KitchenDining • Remove Soda • Add Food 1 • Add Food 2 • Place Order • Close Table • Remove Soda • Food 1 Added • Food 2 Added • Order Placed • Table Closed ES Aggregate 3 2 4 1 The purpose of this example is to demonstrate the concept of ES / CQRS thru Event Storming principles. 3
  • 68. Event Storming Process map – Concept 68 1. Define your User Journey.User Journey DE IE Domain Events Integration Events 7. Events Event(s)Command Micro Service 3. Command & Event(s) BridgeC Commands execute the tasks required to complete the Business Process. Aggregate Root 4. Event Sourced Aggregate Event Sourced Aggregate is derived from a Collection of Events & Factory builds these Aggregate Root Query Name Micro Service 5. Handling Queries in the Process Q Some commands are issued after the User interaction with Query Result Event Listener Micro Service 6. Listener listens for Domain & Integration Events L Listeners plays the key role in Inter Micro Services communications Aggregate Factory 8. Factory Factory Builds the Event Sourced Aggregate Root based on the Business Rules defined. 2. ESP is drawn inside 5 Vertical Swim Lanes. 1. Process Name & User interacting with the App 2. Actions by the user 3. Micro Service(s) involved 4. Events raised due to the command 5. Event Sourced Aggregate Root & Aggregate Factory 3
  • 69. Table OpenedOpen TableC DE 69 ESP : Customer’s Dinning Journey : 1–of–3 Actions Micro Service Events ES Aggregate2 3 4 List Food Menu Food Menu Q Juice AddedAdd JuiceC DE Soda AddedAdd SodaC DE Appetizer 1 AddedAdd Appetizer 1C DE Appetizer 2 AddedAdd Appetizer 2C DE Soda RemovedRemove SodaC DE Food 1 AddedAdd Food 1C DE Order PlacedPlace OrderC IE 1. Dinning Order (This will have all the Events associated with the Customers Dining experience.) 2. Order (Will Contain only the actual order) Dining The purpose of this example is to demonstrate the concept of ES / CQRS thru Event Storming principles. Factory Builds the Aggregates Process 1 Browse Menu Process 2 Order Food Aggregate Root is always derived from the Event Store at the time of the Query. 3
  • 70. 70 ESP : Customer’s Dinning Journey : 2–of–3 Actions Micro Service Events ES Aggregate2 3 4 Table ClosedClose TableC DE Order PlacedOrder Listener DEL Juice ServedServe JuiceC DE IE Soda ServedServe SodaC DE IE Appetizer 1 ServedServe Appetizer 1C DE IE Juice ServedServing Listener DEL Soda ServedServing Listener DEL Appetizer 1 ServedServing Listener DEL Food 1 ServedServing Listener DEL Dining Food PreparedPrepared FoodC DE Food ServedServe FoodC DE IE Kitchen 1. Order Served (This Aggregate Root will help track the Re- Ordering the food Raw materials) 3. Billable Order (This will contain only the Served Item) Aggregate Root is always derived from the Event Store at the time of the Query. Factory Builds the Aggregates Process 4 Serve Food Process 3 Prepare Food 3
  • 71. Payment StatusProcess PaymentC IE 71 ESP : Customer’s Dinning Journey : 3–of–3 Actions Micro Service Events ES Aggregate2 3 4 Payment ApprovedPayment Listener DEL Bill PreparedPrepare BillC DE Payment ProcessedProcess PaymentC DE IEOrder 1. Bill (This will contain only the Served Item) Payment 2. Bill Payment (This will contain the Payment details) Aggregate Root is always derived from the Event Store at the time of the Query. The purpose of this example is to demonstrate the concept of ES / CQRS thru Event Storming principles. Factory Builds the Aggregates Process 5 Make Payment 3
  • 72. Use Case : Shopping Site – Event Sourcing / CQRS 72 Catalogue Shopping Cart Order Payment • Search Products • Add Products • Update Products Commands • Add to Cart • Remove Item • Update Quantity Customer • Process Order • Select Address • Select Delivery Mode Events • Product Added • Product Updated • Product Discontinued • Item Added • Item Removed / Discontinued • Item Updated • Order Initiated • Address Selected • Delivery Mode Selected • Order Created • Proceed for Payment • Confirm Order for Payment • Cancel Order • Payment Initiated • Order Cancelled • Order Confirmed • OTP Send • Payment Approved • Payment Declined Commands are End-User interaction with the App and based on the commands (Actions) Events are created. These Events includes both Domain Events and Integration Events. Event Sourced Aggregates will be derived using Domain Events. Each Micro Service will have its own separate Database. Depends on the scalability requirement each of the Micro Service can be scaled separately. For Example. Catalogue can be on a 50 node cluster compared to Customer Micro Service. Microservices • Customer • Shop.. Cart • Order Customer Journey thru Shopping Process The purpose of this example is to demonstrate the concept of ES / CQRS thru Event Storming principles. 3 2 ES Aggregate 4 3
  • 73. Use Case : Movie Booking – Event Sourcing / CQRS 73 Order Payment • Search Movies • Add Movies • Update Movies Commands • Select Movie • Select Theatre / Show • Select Tickets • Process Order • Select Food • Food Removed • Skip Food • Process Order Events • Movie Added • Movie Updated • Movie Discontinued • Movie Added • Theatre / Show Added • Tickets Added • Order Initiated • Popcorn Added • Drinks Added • Popcorn Removed • Order Finalized • Proceed for Payment • Confirm Order for Payment • Cancel Order • Payment Initiated • Order Cancelled • Order Confirmed • OTP Send • Payment Approved • Payment Declined Movies Theatres Food Microservices Commands are End-User interaction with the App and based on the commands (Actions) Events are created. These Events includes both Domain Events and Integration Events. Event Sourced Aggregates will be derived using Domain Events. Each Micro Service will have its own separate Database. Depends on the scalability requirement each of the Micro Service can be scaled separately. For Example. Theatre can be on a 50 node cluster compared to Food Micro Service. • Theatre • Show • Order Customer Journey thru booking Movie Ticket The purpose of this example is to demonstrate the concept of ES / CQRS thru Event Storming principles. 3 2 ES Aggregate 4 3
  • 74. Use Case : Movie Streaming – Event Sourcing / CQRS 74 Subscription Payment • Search Movies • Add Movies • Update Movies Commands • Request Streaming • Start Movie Streaming • Pause Movie Streaming • Validate Streaming License • Validate Download License Events • Movie Added • Movie Updated • Movie Discontinued • Streaming Requested • Streaming Started • Streaming Paused • Streaming Done • Streaming Request Accepted • Streaming Request Denied • Subscribe Monthly • Subscribe Annually • Monthly Subscription Added • Yearly Subscription Added • Payment Approved • Payment Declined Discovery Microservices Commands are End-User interaction with the App and based on the commands (Actions) Events are created. These Events includes both Domain Events and Integration Events. Event Sourced Aggregates will be derived using Domain Events. Each Micro Service will have its own separate Database. Depends on the scalability requirement each of the Micro Service can be scaled separately. For Example. Theatre can be on a 50 node cluster compared to Food Micro Service. • Stream List • Favorite List Customer Journey thru Streaming Movie / TV Show The purpose of this example is to demonstrate the concept of ES / CQRS thru Event Storming principles. LicenseStreaming 3 2 ES Aggregate 4 3
  • 75. Summary – ESP : Event Sourcing Process map 75 Process1 Commands2 Projections5 ES Aggregate4 Events3 User Journey X Bounded Context Bounded Context Bounded Context Front-End Back-End Database Business Capability 1 Front-End Back-End Database Business Capability 2 Front-End Back-End Database Business Capability 3 Vertically sliced Product Team Ubiquitous Language Domain Expert Analyst Developers QA Design Docs Test Cases Code 3
  • 76. 76 Bounded Context & Hexagonal Architecture • Ports & Adapters – Shopping Portal
  • 77. 77 Hexagonal Architecture Ports & Adapters The layer between the Adapter and the Domain is identified as the Ports layer. The Domain is inside the port, adapters for external entities are on the outside of the port. The notion of a “port” invokes the OS idea that any device that adheres to a known protocol can be plugged into a port. Similarly many adapters may use the Ports. Source : http://alistair.cockburn.us/Hexagonal+architecture https://skillsmatter.com/skillscasts/5744-decoupling-from-asp-net-hexagonal-architectures-in-net Services for UI Ports File system Database Order Tracking JPA Repository Implementation Adapters OrderProcessing Domain Service (Business Rules) Implementation Domain Models Domain Layer Order Data Validation OrderService REST Service Implementation OrderProcessing Interface p Order Tracking Repository Interface p A A External Apps A A A Others A A OrderService Interface p Web Services Data Store Use Case Boundary Bounded Context A • Reduces Technical Debt • Dependency Injection • Auto Wiring 4
  • 78. 78 Specification Guidelines • Approach to understanding the Domain • Discovering Bounded Context
  • 79. Problem Space 79 Source: Patterns, Principles and Practices of DDD – Page xxxvi 5
  • 80. How? 80 Focus on Core Complexity & Opportunity in the Domain Explore models in collaboration of Domain Experts & Software Experts Write software that expresses these Models explicitly Speak Ubiquitous Language within a Bounded Context Eric Evans – Explore DDD, Denver, 2017 5
  • 81. Focus on Clean Boundaries over Perfect Models 81Source: Patterns, Principles and Practices of DDD – Page 38 5
  • 82. How? Core Domain 82 Identity the areas of the business which is critical for the success of the business. Why are these areas important? Why can't we buy a solution rather than building it? What makes the system worth building it? Look at the Core Domain as a Product instead of a Project 5
  • 83. How? Generic Domains 83 An Email Sending Service Notification Services like, SMS, Google Notifications (for Android), iPhone Notifications. Reporting & Dashboard functionalities 5
  • 84. How? Supporting Domains 84 Supporting Domains are the domains that helps the Core Domain. In an E-Commerce application like Amazon or Flipkart, product search functionality is a supporting domain. Even off the shelf application can be used in a supporting domain, For Ex. Ticketing system. 5
  • 85. Solution Space 85Source: Patterns, Principles and Practices of DDD – Page xxxviI 5
  • 86. Domain Vs. Domain Model 86Source: Patterns, Principles and Practices of DDD – Page 43 o Analysis Model or Business Model is to describe the Problem space / Domain. o The Domain Model contains only what is relevant to solve the problem. o Domain Model MUST be free of technical complexities. 5
  • 87. Indicators for Discovering Bounded Context 87 Identify the Business Capabilities from the User Activities / Stories / Use Cases Based on Activities: If an area within the system contains a set of exclusive activities then that’s an indicator for a Business Capabilities. Based on Trigger: Any area which gets automatically triggered based on external input and does some activities based on that trigger. Ex. Spam Checker, Virus Checker in mail attachments. 5
  • 88. Start with? User Journey / Use Cases / Scenarios 88Source: Patterns, Principles and Practices of DDD – Chapter 2 – Page 16 5
  • 89. Activities & User Journey / Ubiquitous Language 89 Process1 Commands2 Projections5 ES Aggregate4 Events3 User Journey X Bounded Context Bounded Context Bounded Context Front-End Back-End Database Business Capability 1 Front-End Back-End Database Business Capability 2 Front-End Back-End Database Business Capability 3 Vertically sliced Product Team Ubiquitous Language Domain Expert Analyst Developers QA Design Docs Test Cases Code 5
  • 90. List Core Activities 90 o List Code Activities for the Primary Use Case o Identify the Business Function / Capabilities of each of the Activity o Identify the User Role (Actor) for this Activity, o Ensure that the list of the Activities complete the entire Business Solution. Activity Business Function Actor 1 2 3 4 5 6 7 8 9 10 5
  • 91. User Journey: Shopping in E-Commerce Site 91 Catalogue Shopping Cart Order Payment • Search Products • Add Products • Update Products Commands • Add to Cart • Remove Item • Update Quantity Customer • Process Order • Select Address • Select Delivery Mode Events • Product Added • Product Updated • Product Discontinued • Item Added • Item Removed / Discontinued • Item Updated • Order Initiated • Address Selected • Delivery Mode Selected • Order Created • Proceed for Payment • Confirm Order for Payment • Cancel Order • Payment Initiated • Order Cancelled • Order Confirmed • OTP Send • Payment Approved • Payment Declined Commands are End-User interaction with the App and based on the commands (Actions) Events are created. These Events includes both Domain Events and Integration Events. Event Sourced Aggregates will be derived using Domain Events. Each Micro Service will have its own separate Database. Depends on the scalability requirement each of the Micro Service can be scaled separately. For Example. Catalogue can be on a 50 node cluster compared to Customer Micro Service. Microservices • Customer • Shop.. Cart • Order Customer Journey thru Shopping Process The purpose of this example is to demonstrate the concept of ES / CQRS thru Event Storming principles. 3 2 ES Aggregate 4 5
  • 92. Cart OpenedOpen CartC DE 92 ESP : Customer’s Shopping Journey Actions Micro Service Events ES Aggregate2 3 4 List Product Menu Product Menu Q Book AddedAdd BookC DE Pen AddedAdd PenC DE Bag AddedAdd BagC DE Book 2 AddedAdd Book 2C DE Book 3 AddedAdd Book 3C DE Book 2 RemovedRemove Book 2C DE Order PlacedPlace OrderC IE 1. Shopping Cart (This will have all the Events associated with the Customers Shopping experience.) 2. Order (Will Contain only the actual order) Shopping Cart Factory Builds the Aggregates Process 1 Browse Catalogue Process 2 Do Shopping Aggregate Root is always derived from the Event Store at the time of the Query. 5
  • 93. 93 Ubiquitous Language Vocabulary shared by all involved parties Used in all forms of spoken / written communication Ubiquitous Language Domain Expert Analyst Developers QA Design Docs Test Cases Code E-Commerce Context - Product: Eg. In an E-Commerce Domain the Product can have different meanings in different context. • Product Context in Catalogue will have product ID, image, descriptions etc. • Product Context in the Inventory will keep track of info like SKU, product technical details from storage perspective. Use Case Scenarios – Ubiquitous Language & BDD As an E-Commerce Owner I want to know who my Customers are So that I can serve them better with free delivery / discounts Role-Feature-Reason Matrix BDD – Behavior Driven Development Given Customer John Doe exists When Customer orders items Then Assign Customer preference based Item Category and keep the count of items. BDD Construct 5
  • 94. User Case Scenarios – Behavior Driven Development 94 As an E-Commerce Owner I want know my premium Customers So that I can offer free delivery Role-Feature-Reason Matrix Given Threshold for free delivery is set at $70 and I am Customer who has a basket totaling $50 When I add an item to my basket costing $21 Then I should be offered free delivery BDD Construct Customer Offerings Shopping Cart Order Business Capabilities Bounded Context Given Threshold for free delivery is set at $70 and I am Customer who has a basket totaling $60 When I add an item to my basket costing $7 Then if I increase my total purchase value by $3 then I will be offered free Delivery. BDD Construct Scenario 1 Scenario 2 5
  • 95. 95 Implementation Guidelines • Hexagonal Architecture • Ports & Adapters – Shopping Portal • RESTful Guidelines
  • 96. 96 Hexagonal Architecture Ports & Adapters The layer between the Adapter and the Domain is identified as the Ports layer. The Domain is inside the port, adapters for external entities are on the outside of the port. The notion of a “port” invokes the OS idea that any device that adheres to a known protocol can be plugged into a port. Similarly many adapters may use the Ports. Source : http://alistair.cockburn.us/Hexagonal+architecture https://skillsmatter.com/skillscasts/5744-decoupling-from-asp-net-hexagonal-architectures-in-net Services for UI Ports File system Database Order Tracking JPA Repository Implementation Adapters OrderProcessing Domain Service (Business Rules) Implementation Domain Models Domain Layer Order Data Validation OrderService REST Service Implementation OrderProcessing Interface p Order Tracking Repository Interface p A A External Apps A A A Others A A OrderService Interface p Web Services Data Store Use Case Boundary Bounded Context A • Reduces Technical Debt • Dependency Injection • Auto Wiring 5
  • 97. Shopping Portal Modules – Code Packaging 97 Auth Products Cart OrderCustomer Domain Layer • Models • Repo • Services • Factories Adapters • Repo • Services • Web Services Domain Layer • Models • Repo • Services • Factories Adapters • Repo • Services • Web Services Domain Layer • Models • Repo • Services • Factories Adapters • Repo • Services • Web Services Packaging Structure Bounded Context Implementation (Repositories, Business Services, Web Services) Domain Models (Entities, Value Objects, DTOs) (Repositories, Business Services, Web Services) Entity Factories Interfaces (Ports) 5
  • 98. Shopping Portal 98 Order Bounded Context Models Value Object • Currency • Item Value • Order Status • Payment Type • Record State • Audit Log Entity • Order (Aggregate Root) • Order Item • Shipping Address • Payment DTO • Order • Order Item • Shipping Address • Payment Domain Layer Adapters • Order Repository • Order Service • Order Web Service • Order Query Web Service • Shipping Address Web Service • Payment Web Service Adapters Consists of Actual Implementation of the Ports like Database Access, Web Services API etc. Converters are used to convert an Enum value to a proper Integer value in the Database. For Example Order Status Complete is mapped to integer value 100 in the database. Services / Ports • Order Repository • Order Service • Order Web Service Utils • Order Factory • Order Status Converter • Record State Converter • Order Query Web Service • Shipping Address Web Service • Payment Web Service 5
  • 99. Shopping Portal Design based on Hexagonal Architecture 99 5
  • 100. RESTful Guidelines 100 1. Endpoints as nouns, NOT verbs Ex. /catalogues /orders /catalogues/products and NOT /getProducts/ /updateProducts/ 2. Use plurals Ex. /catalogues/{catalogueId} and NOT /catalogue/{catalogueId} 3. Documenting 4. Paging 5. Use SSL 6. HTTP Methods GET / POST / PUT / DELETE / OPTIONS / HEAD 7. HTTP Status Codes (Effective usage) 8. Versioning Media Type Version GET /account/5555 HTTP/1.1 Accept: application/vnd.catalogues.v1+json URL path version https://domain/v1/catalogues/products 5
  • 101. RESTful Guidelines – Query Examples 101 Search All Products Search Products By Catalogue ID Search Products By Catalogue ID & Product ID 5
  • 102. RESTful Guidelines – Query Examples 102 Two different implementation of same query 5
  • 103. RESTful Guidelines – Get & Create Example 103 URL Remains the same. HTTP Methods Get / Post Defines the action 5
  • 104. RESTful Guidelines – Update & Delete Example 104 5
  • 105. 105 Design Patterns are solutions to general problems that software developers faced during software development. Design Patterns – Holy Grail of Developers 5
  • 106. References 106 Domain Driven Design 16. Oct 27, 2012 What I have learned about DDD Since the book. By Eric Evans 17. Mar 19, 2013 Domain Driven Design By Eric Evans 18. May 16, 2015 Microsoft Ignite: Domain Driven Design for the Database Driven Mind 19. Jun 02, 2015 Applied DDD in Java EE 7 and Open Source World 20. Aug 23, 2016 Domain Driven Design the Good Parts By Jimmy Bogard 21. Sep 22, 2016 GOTO 2015 – DDD & REST Domain Driven API’s for the Web. By Oliver Gierke 22. Jan 24, 2017 Spring Developer – Developing Micro Services with Aggregates. By Chris Richardson 23. May 17. 2017 DEVOXX – The Art of Discovering Bounded Contexts. By Nick Tune Event Sourcing and CQRS 23. Nov 13, 2014 GOTO 2014 – Event Sourcing. By Greg Young 24. Mar 22, 2016 Spring Developer – Building Micro Services with Event Sourcing and CQRS 25. Apr 15, 2016 YOW! Nights – Event Sourcing. By Martin Fowler 26. May 08, 2017 When Micro Services Meet Event Sourcing. By Vinicius Gomes
  • 107. References 107 27. MSDN – Microsoft https://msdn.microsoft.com/en-us/library/dn568103.aspx 28. Martin Fowler : CQRS – http://martinfowler.com/bliki/CQRS.html 29. Udi Dahan : CQRS – http://www.udidahan.com/2009/12/09/clarified-cqrs/ 30. Greg Young : CQRS - https://www.youtube.com/watch?v=JHGkaShoyNs 31. Bertrand Meyer – CQS - http://en.wikipedia.org/wiki/Bertrand_Meyer 32. CQS : http://en.wikipedia.org/wiki/Command–query_separation 33. CAP Theorem : http://en.wikipedia.org/wiki/CAP_theorem 34. CAP Theorem : http://www.julianbrowne.com/article/viewer/brewers-cap-theorem 35. CAP 12 years how the rules have changed 36. EBay Scalability Best Practices : http://www.infoq.com/articles/ebay-scalability-best-practices 37. Pat Helland (Amazon) : Life beyond distributed transactions 38. Stanford University: Rx https://www.youtube.com/watch?v=y9xudo3C1Cw 39. Princeton University: SAGAS (1987) Hector Garcia Molina / Kenneth Salem 40. Rx Observable : https://dzone.com/articles/using-rx-java-observable
  • 108. References – Micro Services – Videos 41. Martin Fowler – Micro Services : https://www.youtube.com/watch?v=2yko4TbC8cI&feature=youtu.be&t=15m53s 42. GOTO 2016 – Microservices at NetFlix Scale: Principles, Tradeoffs & Lessons Learned. By R Meshenberg 43. Mastering Chaos – A NetFlix Guide to Microservices. By Josh Evans 44. GOTO 2015 – Challenges Implementing Micro Services By Fred George 45. GOTO 2016 – From Monolith to Microservices at Zalando. By Rodrigue Scaefer 46. GOTO 2015 – Microservices @ Spotify. By Kevin Goldsmith 47. Modelling Microservices @ Spotify : https://www.youtube.com/watch?v=7XDA044tl8k 48. GOTO 2015 – DDD & Microservices: At last, Some Boundaries By Eric Evans 49. GOTO 2016 – What I wish I had known before Scaling Uber to 1000 Services. By Matt Ranney 50. DDD Europe – Tackling Complexity in the Heart of Software By Eric Evans, April 11, 2016 51. AWS re:Invent 2016 – From Monolithic to Microservices: Evolving Architecture Patterns. By Emerson L, Gilt D. Chiles 52. AWS 2017 – An overview of designing Microservices based Applications on AWS. By Peter Dalbhanjan 53. GOTO Jun, 2017 – Effective Microservices in a Data Centric World. By Randy Shoup. 54. GOTO July, 2017 – The Seven (more) Deadly Sins of Microservices. By Daniel Bryant 55. Sept, 2017 – Airbnb, From Monolith to Microservices: How to scale your Architecture. By Melanie Cubula 56. GOTO Sept, 2017 – Rethinking Microservices with Stateful Streams. By Ben Stopford. 57. GOTO 2017 – Microservices without Servers. By Glynn Bird. 108
  • 109. 109 Araf Karsh Hamid : Co-Founder / CTO araf.karsh@metamagic.in USA: +1 (973) 969-2921 India: +91.999.545.8627 Skype / LinkedIn / Twitter / Slideshare : arafkarsh http://www.slideshare.net/arafkarsh https://www.linkedin.com/in/arafkarsh/ http://www.arafkarsh.com/
  • 110. JPA 2.2 and JDBC 110 Java Type JDBC Type java.time.LocalDate DATE java.time.LocalTime TIME java.time.LocalDateTime TIMESTAMP java.time.OffsetTime TIME_WITH_TIMEZONE java.time.OffsetDateTime TIMESTAMP_WITH_TIMEZONE

Hinweis der Redaktion

  1. https://www.forrester.com/report/Application+Modernization+Service+By+Microservice/-/E-RES122550 https://www.forrester.com/report/Microservices+And+External+APIs+Underpin+Digital+Business/-/E-RES137951 e(l(44)/3) = 3.5
  2. Analytics = Score = 3 + 5 + 3 = 11 WS = 1.05 + 1.25 + 1.2 = 3.50 Shopping Cart Score = 5 + 3 + 3 = 11 WS = 1.75 + 0.75 + 1.2 = 3.70 Customer Score = 3 + 3 + 1 = 7 WS = 1.05 + 0.75 + 0.40 = 2.20 Catalogue Score = 3 + 3 + 5 = 11 WS = 1.05 + 0.75 + 2 = 4.80 Order Score = 7 + 3 + 5 = 15 WS = 2.45 + 0.75 + 2 = 5.20 Inventory Score = 7 + 5 + 3 = 15 WS = 2.45 +
  3. http://domainlanguage.com/ddd/patterns/DDD_Reference_2011-01-31.pdf http://www.infoq.com/interviews/domain-driven-design-eric-evans
  4. http://martinfowler.com/bliki/DDD_Aggregate.html Effective Aggregate Design By Vaughn Vernon Part 1 : http://dddcommunity.org/wp-content/uploads/files/pdf_articles/Vernon_2011_1.pdf Part 2 : http://dddcommunity.org/wp-content/uploads/files/pdf_articles/Vernon_2011_2.pdf Part 3 : http://dddcommunity.org/wp-content/uploads/files/pdf_articles/Vernon_2011_3.pdf Video Part 2 : https://vimeo.com/33708293
  5. References https://docs.microsoft.com/en-us/dotnet/standard/microservices-architecture/microservice-ddd-cqrs-patterns/domain-events-design-implementation
  6. http://reactivex.io/documentation/observable.html
  7. http://reactivex.io/RxJava/javadoc/rx/observables/BlockingObservable.html
  8. https://en.wikipedia.org/wiki/Data_transfer_object#cite_note-fowlerLocalDTO-3 http://martinfowler.com/eaaCatalog/dataTransferObject.html http://www.adam-bien.com/roller/abien/entry/javaee_7_retired_the_dto http://www.adam-bien.com/roller/abien/entry/value_object_vs_data_transfer
  9. https://en.wikipedia.org/wiki/Data_transfer_object#cite_note-fowlerLocalDTO-3 http://martinfowler.com/eaaCatalog/dataTransferObject.html http://www.adam-bien.com/roller/abien/entry/javaee_7_retired_the_dto http://www.adam-bien.com/roller/abien/entry/value_object_vs_data_transfer http://www.oracle.com/technetwork/java/transferobject-139757.html http://www.adam-bien.com/roller/abien/entry/a_good_architecture_is_all http://www.oracle.com/technetwork/java/transferobject-139757.html https://msdn.microsoft.com/en-us/library/ms978717.aspx
  10. http://www.javaworld.com/article/2078042/java-app-dev/domain-driven-design-with-java-ee-6.html
  11. https://martinfowler.com/bliki/BusinessCapabilityCentric.html
  12. References https://docs.microsoft.com/en-us/dotnet/standard/microservices-architecture/microservice-ddd-cqrs-patterns/domain-events-design-implementation