SlideShare a Scribd company logo
1 of 57
ROME 11-12 april 2014ROME 11-12 april 2014
Moving Away From CRUD: Domain Driven Design (DDD) and
Command Query Responsibility Segregation (CQRS)
Email: forat.latif@gmail.com
Twitter: @foratlatif
Forat Latif
ROME 11-12 april 2014 - Speaker’s name
Time to start a greenfield project
ROME 11-12 april 2014 - Speaker’s name
Process
1) Gather Requirements
2) Model our “Entities”
3) Scaffold our projects and our database based on those entities
ROME 11-12 april 2014 - Speaker’s name
What the Architecture looks like?
ROME 11-12 april 2014 - Speaker’s name
Our Domain
class Product {
String name;
String
description;
Integer price;
Integer discount;
String category;
}
class Customer {
Address address;
String name;
}
class Order {
String
description;
Customer
customer;
List<LineItems>
lineItems;
}
class LineItem {
Product product;
}
ROME 11-12 april 2014 - Speaker’s name
Just what do we mean by Entity?
class Product {
String name;
String description;
Integer price;
Integer discount;
String category;
String getDescription() {
return this.description;
}
void setDescription(String aDescription) {
this.description = aDescription;
}
String getName() {
…….
……
}
ROME 11-12 april 2014 - Speaker’s name
So … Where is the business logic?
class ProductService {
public void discountProduct(String productId, Integer discount) {
Product product = productRepository.find(productId);
product.setDiscount(discount);
if (discount > 30) {
product.setStatus(“Super Discount”);
}
productRepository.save(aProduct);
}
}
ROME 11-12 april 2014 - Speaker’s name
So … Where is the business logic?
class ProductController {
public void updateProduct(Product product) {
productRepository.save(product);
}
}
ROME 11-12 april 2014 - Speaker’s name
Are we really doing OOP?
Objects are supposed to have a
state and behavior that modifies
that state
State shouldn’t be exposed (getters
and setters are not encapsulation)
Objects should be loosely coupled
Business rules should be placed in
one place
class Product {
String name;
String description;
String category;
String getName() {
return this.description;
}
void setName(String name) {
this.name= name;
}
String getPrice() {
…….
……
}
ROME 11-12 april 2014 - Speaker’s name
Implicit Business Rules
class PromoService {
void discountProduct (String productId, Integer discount) {
Product product = productRepository.find(productId);
product.setDiscount(discount);
if (discount > 30) {
product.setStatus(“Super Discount”);
}
}
}
class AnotherService {
void discountSomethinElse (String productId) {
Product product = productRepository.find(productId);
someValue = calculateValue();
product.setDiscount(someValue);
}
}
ROME 11-12 april 2014 - Speaker’s name
Objects should expose BEHAVIOR
class Product {
String name;
String status;
Integer price;
Integer discount;
String category;
void discount(Integer discount) {
this.discount = discount;
if (discount > 30) {
this.status = “Super Discount”;
}
}
}
ROME 11-12 april 2014 - Speaker’s name
Back to our “Entities”
class Customer {
String name;
Address address;
}
class Address {
String street;
Integer streetNumber;
}
ROME 11-12 april 2014 - Speaker’s name
Entities and Value Objects
Entities in DDD are not defined by their attributes, they are defined
by a conceptual identity and we care about its changes
Value Objects represent a description of something at a certain
point in time. Thats why they are immutable and we care only
about its attributes
ROME 11-12 april 2014 - Speaker’s name
What a purchase looks like
class OrderService {
@Transactional
public void purchaseOrder(String orderId) {
Order order = orderRepository .find(orderId);
order.purchase();
productService.removeFromInventory(order.products());
emailService.sendConfirmationEmail(order);
}
}
ROME 11-12 april 2014 - Speaker’s name
Suddenly our mail server goes
down …
ROME 11-12 april 2014 - Forat Latif
Domain Events
A Domain Event, represents something that already
happened, that is relevant to the business
ROME 11-12 april 2014 - Forat Latif
Domain Events
class Service {
void handle(SomeEvent event) {
doSomething();
}
}
ROME 11-12 april 2014 - Forat Latif
Domain Events
class OrderService {
@Transactional
public void purchaseOrder(String orderId) {
Order order = orderRepository .find(orderId);
order.purchase();
productService.removeFromInventory(order.products());
eventBus.push(new OrderPurchased(order.orderId());
}
}
class EmailSender {
public void handle(OrderPurchased orderPurchased) {
Order order = orderRepository.find(orderPurchased.orderId);
emailService.sendConfirmationEmail(order);
}
}
ROME 11-12 april 2014 - Forat Latif
Sales of a Product skyrocket ….
ROME 11-12 april 2014 - Forat Latif
Eventual Consistency
class OrderService {
@Transactional
public void purchaseOrder(String orderId) {
Order order = orderRepository .find(orderId);
order.purchase();
eventBus.push(new OrderPurchased(order.orderId());
}
}
class OrderProcessManager {
public void handle(OrderPurchased orderPurchased) {
Order order = orderRepository.find(orderPurchased.orderId);
productService.removeFromInventory(order.products());
}
}
ROME 11-12 april 2014 - Forat Latif
Aggregate Roots
Aggregate is a pattern in Domain-Driven Design. A DDD
aggregate is a cluster of domain objects that can be treated as a
single unit.
An aggregate has a root that acts as an outside interface and
keeps all invariants inside the aggregate.
Each request should strive to load one aggregate and execute a
single operation on it.
Hence, Aggregates guarantee transactional consistency inside its
boundaries
ROME 11-12 april 2014 - Forat Latif
What our new Architecture looks
like
ROME 11-12 april 2014 - Forat Latif
Product Inventory and Catalog
class Product {
String name;
Integer price;
Integer priceFromSupplier;
String supplier;
String shippingStatus;
String shippingMethod;
}
ROME 11-12 april 2014 - Forat Latif
Bounded Contexts
Explicitly define the context within which a model applies. Explicitly
set boundaries in terms of team organization, usage within specific
parts of the application, and physical manifestations such as code
bases and database schemas. Keep the model strictly consistent
within these bounds, but don’t be distracted or confused by issues
outside.
Inventory
E-commerce
Shipping
ROME 11-12 april 2014 - Forat Latif
Bounded Contexts
class Product {
String name;
Integer price;
} class Item {
String shippingStatus;
String shippingMethod;
}
class Product {
Integer priceFromSupplier;
String supplier;
}
E-Commerce Context
Inventory Context
Shipping Context
ROME 11-12 april 2014 - Forat Latif
Communication between BCs
Inventory
E-commerce
Shipping
ROME 11-12 april 2014 - Forat Latif
How to identify BCs
Ubiquitous Language
Goals and Concerns
Teams
Organizational Structure
ROME 11-12 april 2014 - Forat Latif
So .. just what is DDD?
Domain Driven Design is an approach to software development in
which the Domain is the center of attention.
- Strategic Design
- Tactical Design
We should focus on what matters, and thats adding value to our
business through software, the software itself is just a byproduct of
our strategy
ROME 11-12 april 2014 - Forat Latif
What about User Interfaces?
class ProductController {
Product viewProduct (String productId) {
Product product = productRepository.find(productId);
return product;
}
}
ROME 11-12 april 2014 - Forat Latif
User dashboard
ROME 11-12 april 2014 - Forat Latif
User Dashboard
class ProductController {
ProductDTO viewProduct (String productId) {
//Solution 1: Do a manual query and map it to the DTO
//Solution 2: Use your ORM to get all the objects you need
// and map them to the DTO
return productDTO;
}
}
ROME 11-12 april 2014 - Forat Latif
List the products of a category
ROME 11-12 april 2014 - Forat Latif
Category Tree
ROME 11-12 april 2014 - Forat Latif
Category Tree Model
class Category {
String name;
Category parent;
}
class Product{
Category category;
}
ROME 11-12 april 2014 - Forat Latif
“Simple” change request …
ROME 11-12 april 2014 - Forat Latif
Possible Solutions
Nested Query:
with CTQ as (
select * from Categories c where c.parentId = 1
union all
select * from CTQ p, Categories c where c.parentId =
p.categoryId
)
select * from CTQ
ROME 11-12 april 2014 - Forat Latif
Possible Solutions
Modify The domain:
//Impedance Mismatch Pain
class Category {
List<Product> products;
List<Category> children;
}
class Product {
Category category;
}
ROME 11-12 april 2014 - Forat Latif
Possible Solutions
Another possibility:
class Category {
String parent1Id;
String parent2Id;
String parent3Id;
….
String categoryId;
String name;
}
ROME 11-12 april 2014 - Forat Latif
Command Query Separation (CQS)
Principle
Command–query separation (CQS) is a principle that states that
every method should either be a command that performs an
action, or a query that returns data to the caller, but not both. In
other words, asking a question should not change the answer
Commands and Queries have different concerns
ROME 11-12 april 2014 - Forat Latif
Command Query Responsibility
Segregation (CQRS)
We can do CQS at the architectural level too .....
class CategoryReadService{
List<Categories> getChildrenCategories(String categoriId);
}
class CategoryWriteService{
void addCategory (String parendId, String name);
}
ROME 11-12 april 2014 - Forat Latif
Command Query Responsibility
Segregation (CQRS)
where are do we need to do queries? when returning a DTO, not
when performing a write operation
when it comes to queries just query the database, why load a
behavioral object to show data on a screen?
You should modify your domain objects only when you need that
change for write operations.
If queries become too complex thats another sign that they are two
different concerns
ROME 11-12 april 2014 - Forat Latif
Back to the User Dashboard
ROME 11-12 april 2014 - Forat Latif
User Dashboard with CQRS
class UserDashboardProjector {
handle(ProductAdded productAdded) {
//insert into “user dashboard entry” with the data in the event
}
handle(ProductShipped productShipped) {
//update “user dashboard entry” with the data in the event
}
}
class ProductQueryProcessor {
List<UserDashboardEntryDTO> getProducts(String userId) {
//Select from “user dashboard entry” where userId =
userId
}
}
ROME 11-12 april 2014 - Forat Latif
Category Tree with CQRS
ROME 11-12 april 2014 - Forat Latif
Category Tree with CQRS
Books
Technical
Accademi
c
DDD Blue
Book
Some
Weird
Book
Category
Book Book
Category
ROME 11-12 april 2014 - Forat Latif
Category Tree with CQRS
class CategoryProjector {
handle(CategoryAdded categoryAdded) {
Vertex child = createVertex();
child.setProperty(“name”, categoryAdded.name());
Vertex parent = getVertex(categoryAdded.parentId());
parent.addEdge(child);
}
}
class ProductQueryProcessor {
List<ProductDTO> getProducts(String categoryId) {
// graph query to get all children of type x;
}
}
ROME 11-12 april 2014 - Forat Latif
Multiple categories
ROME 11-12 april 2014 - Forat Latif
Multiple categories
Without CQRS:
Nested Query : ….
Modify the domain (even more Impedance mismatch pain)
Mixed: (join table unavoidable)
ROME 11-12 april 2014 - Forat Latif
Multiple categories
With CQRS:
class Product {
List<Categories> categories;
}
and … thats it! The read model doesnt need to be modified
ROME 11-12 april 2014 - Forat Latif
Notice a pattern?
Read model is data driven
Write model is Domain Driven (database not important)
To design your write model you can imagine that you dont need a
database (you have infinite persisant RAM)
ROME 11-12 april 2014 - Forat Latif
Aggregates as Documents
- consistency easier to maintain,
- performance
- scalability
- technical simplicity (no lazy load config nor impedence
mismatch)
class Product {
String productId;
@EmbedSomehow // hopefully with a doc database
List<String> categoryIds;
}
ROME 11-12 april 2014 - Forat Latif
Commands
class OrderService {
@Transactional
public void purchaseOrder(String orderId) {
……
}
}
class PurchaseOrderCommandHandler {
@Transactional
public void handle(PurchaseOrderCommand command) {
……
}
}
ROME 11-12 april 2014 - Forat Latif
Advantages of Commands
Command log (not your regular log)
Clear user intention
Improved Testability
Integration
Get rid of AOP
Command Sourcing
ROME 11-12 april 2014 - Forat Latif
Advantages of Commands
Represent an intention, which usually maps to a command method
in your aggregate, which causes one or many events to be
pushed.
class ChangeCustomerTelephoneCommandHandler {
@Transactional
public void handle(ChangeCustomerTelephoneCommand command) {
……
}
}
ROME 11-12 april 2014 - Forat Latif
Overview of CQRS
ROME 11-12 april 2014 - Forat Latif
Recap of CQRS
CQS is a principle that can be applied at the architecturale level.
Read and Write are two separate concerns
You cannot solve all problems with the same model, especially if
the problem domains have different points of view
ROME 11-12 april 2014ROME 11-12 april 2014
Moving Away From CRUD: Domain Driven Design (DDD) and
Command Query Responsibility Segregation (CQRS)
Forat Latif
Email: forat.latif@gmail.com
Twitter: @foratlatif
Questions?

More Related Content

Similar to Ddd cqrs - Forat Latif

Introduction to Wildfly 8 - Marchioni
Introduction to Wildfly 8 -  MarchioniIntroduction to Wildfly 8 -  Marchioni
Introduction to Wildfly 8 - MarchioniCodemotion
 
SCM-APO-PP/DS-Production Planning and Detailed Scheduling
SCM-APO-PP/DS-Production Planning and Detailed SchedulingSCM-APO-PP/DS-Production Planning and Detailed Scheduling
SCM-APO-PP/DS-Production Planning and Detailed SchedulingAJAY
 
E-Business Suite Release 12 Payables Upgrade: Like for Like and Then Some
E-Business Suite Release 12 Payables Upgrade: Like for Like and Then SomeE-Business Suite Release 12 Payables Upgrade: Like for Like and Then Some
E-Business Suite Release 12 Payables Upgrade: Like for Like and Then Someeprentise
 
DDD on example of Symfony (Webcamp Odessa 2014)
DDD on example of Symfony (Webcamp Odessa 2014)DDD on example of Symfony (Webcamp Odessa 2014)
DDD on example of Symfony (Webcamp Odessa 2014)Oleg Zinchenko
 
OOP Is More Than Cars and Dogs
OOP Is More Than Cars and DogsOOP Is More Than Cars and Dogs
OOP Is More Than Cars and DogsChris Tankersley
 
Object Graph Mapping with Spring Data Neo4j 3 - Nicki Watt & Michael Hunger @...
Object Graph Mapping with Spring Data Neo4j 3 - Nicki Watt & Michael Hunger @...Object Graph Mapping with Spring Data Neo4j 3 - Nicki Watt & Michael Hunger @...
Object Graph Mapping with Spring Data Neo4j 3 - Nicki Watt & Michael Hunger @...Neo4j
 
Learned lessons in a real world project by Luis Rovirosa at PHPMad
Learned lessons in a real world project by Luis Rovirosa at PHPMadLearned lessons in a real world project by Luis Rovirosa at PHPMad
Learned lessons in a real world project by Luis Rovirosa at PHPMadCodium
 
UKOUG Tech15 - Going Full Circle - Building a native JSON Database API
UKOUG Tech15 - Going Full Circle - Building a native JSON Database APIUKOUG Tech15 - Going Full Circle - Building a native JSON Database API
UKOUG Tech15 - Going Full Circle - Building a native JSON Database APIMarco Gralike
 
Mind Your Business. And Its Logic
Mind Your Business. And Its LogicMind Your Business. And Its Logic
Mind Your Business. And Its LogicVladik Khononov
 
Unit Test for ZF SlideShare Component
Unit Test for ZF SlideShare ComponentUnit Test for ZF SlideShare Component
Unit Test for ZF SlideShare ComponentKaiuwe
 
Unit Test for ZF SlideShare Component
Unit Test for ZF SlideShare ComponentUnit Test for ZF SlideShare Component
Unit Test for ZF SlideShare ComponentKaiuwe
 
Dissecting and Attacking RMI Frameworks
Dissecting and Attacking RMI FrameworksDissecting and Attacking RMI Frameworks
Dissecting and Attacking RMI FrameworksOnapsis Inc.
 
Oracle Database 12c Feature Support in Oracle SQL Developer
Oracle Database 12c Feature Support in Oracle SQL DeveloperOracle Database 12c Feature Support in Oracle SQL Developer
Oracle Database 12c Feature Support in Oracle SQL DeveloperJeff Smith
 
Webcast: Identify and Correct Common Code Smells
Webcast: Identify and Correct Common Code SmellsWebcast: Identify and Correct Common Code Smells
Webcast: Identify and Correct Common Code SmellsSerge Baranovsky
 
Umesh_Pacholi_ORPOS_Consultant_9yrs_Team_Lead
Umesh_Pacholi_ORPOS_Consultant_9yrs_Team_LeadUmesh_Pacholi_ORPOS_Consultant_9yrs_Team_Lead
Umesh_Pacholi_ORPOS_Consultant_9yrs_Team_LeadUmesh Pacholi
 
PHPBootcamp - Zend Framework
PHPBootcamp - Zend FrameworkPHPBootcamp - Zend Framework
PHPBootcamp - Zend Frameworkthomasw
 

Similar to Ddd cqrs - Forat Latif (18)

Introduction to Wildfly 8 - Marchioni
Introduction to Wildfly 8 -  MarchioniIntroduction to Wildfly 8 -  Marchioni
Introduction to Wildfly 8 - Marchioni
 
SCM-APO-PP/DS-Production Planning and Detailed Scheduling
SCM-APO-PP/DS-Production Planning and Detailed SchedulingSCM-APO-PP/DS-Production Planning and Detailed Scheduling
SCM-APO-PP/DS-Production Planning and Detailed Scheduling
 
E-Business Suite Release 12 Payables Upgrade: Like for Like and Then Some
E-Business Suite Release 12 Payables Upgrade: Like for Like and Then SomeE-Business Suite Release 12 Payables Upgrade: Like for Like and Then Some
E-Business Suite Release 12 Payables Upgrade: Like for Like and Then Some
 
DDD on example of Symfony (Webcamp Odessa 2014)
DDD on example of Symfony (Webcamp Odessa 2014)DDD on example of Symfony (Webcamp Odessa 2014)
DDD on example of Symfony (Webcamp Odessa 2014)
 
OOP Is More Than Cars and Dogs
OOP Is More Than Cars and DogsOOP Is More Than Cars and Dogs
OOP Is More Than Cars and Dogs
 
Session 203 iouc summit database
Session 203 iouc summit databaseSession 203 iouc summit database
Session 203 iouc summit database
 
Object Graph Mapping with Spring Data Neo4j 3 - Nicki Watt & Michael Hunger @...
Object Graph Mapping with Spring Data Neo4j 3 - Nicki Watt & Michael Hunger @...Object Graph Mapping with Spring Data Neo4j 3 - Nicki Watt & Michael Hunger @...
Object Graph Mapping with Spring Data Neo4j 3 - Nicki Watt & Michael Hunger @...
 
Learned lessons in a real world project by Luis Rovirosa at PHPMad
Learned lessons in a real world project by Luis Rovirosa at PHPMadLearned lessons in a real world project by Luis Rovirosa at PHPMad
Learned lessons in a real world project by Luis Rovirosa at PHPMad
 
UKOUG Tech15 - Going Full Circle - Building a native JSON Database API
UKOUG Tech15 - Going Full Circle - Building a native JSON Database APIUKOUG Tech15 - Going Full Circle - Building a native JSON Database API
UKOUG Tech15 - Going Full Circle - Building a native JSON Database API
 
Mind Your Business. And Its Logic
Mind Your Business. And Its LogicMind Your Business. And Its Logic
Mind Your Business. And Its Logic
 
Unit Test for ZF SlideShare Component
Unit Test for ZF SlideShare ComponentUnit Test for ZF SlideShare Component
Unit Test for ZF SlideShare Component
 
Unit Test for ZF SlideShare Component
Unit Test for ZF SlideShare ComponentUnit Test for ZF SlideShare Component
Unit Test for ZF SlideShare Component
 
Dissecting and Attacking RMI Frameworks
Dissecting and Attacking RMI FrameworksDissecting and Attacking RMI Frameworks
Dissecting and Attacking RMI Frameworks
 
Zend Framework
Zend FrameworkZend Framework
Zend Framework
 
Oracle Database 12c Feature Support in Oracle SQL Developer
Oracle Database 12c Feature Support in Oracle SQL DeveloperOracle Database 12c Feature Support in Oracle SQL Developer
Oracle Database 12c Feature Support in Oracle SQL Developer
 
Webcast: Identify and Correct Common Code Smells
Webcast: Identify and Correct Common Code SmellsWebcast: Identify and Correct Common Code Smells
Webcast: Identify and Correct Common Code Smells
 
Umesh_Pacholi_ORPOS_Consultant_9yrs_Team_Lead
Umesh_Pacholi_ORPOS_Consultant_9yrs_Team_LeadUmesh_Pacholi_ORPOS_Consultant_9yrs_Team_Lead
Umesh_Pacholi_ORPOS_Consultant_9yrs_Team_Lead
 
PHPBootcamp - Zend Framework
PHPBootcamp - Zend FrameworkPHPBootcamp - Zend Framework
PHPBootcamp - Zend Framework
 

More from Codemotion

Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...Codemotion
 
Pompili - From hero to_zero: The FatalNoise neverending story
Pompili - From hero to_zero: The FatalNoise neverending storyPompili - From hero to_zero: The FatalNoise neverending story
Pompili - From hero to_zero: The FatalNoise neverending storyCodemotion
 
Pastore - Commodore 65 - La storia
Pastore - Commodore 65 - La storiaPastore - Commodore 65 - La storia
Pastore - Commodore 65 - La storiaCodemotion
 
Pennisi - Essere Richard Altwasser
Pennisi - Essere Richard AltwasserPennisi - Essere Richard Altwasser
Pennisi - Essere Richard AltwasserCodemotion
 
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...Codemotion
 
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019Codemotion
 
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019Codemotion
 
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Francesco Baldassarri  - Deliver Data at Scale - Codemotion Amsterdam 2019 - Francesco Baldassarri  - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 - Codemotion
 
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...Codemotion
 
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...Codemotion
 
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...Codemotion
 
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...Codemotion
 
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019Codemotion
 
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019Codemotion
 
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019Codemotion
 
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...Codemotion
 
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...Codemotion
 
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019Codemotion
 
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019Codemotion
 
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019Codemotion
 

More from Codemotion (20)

Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
 
Pompili - From hero to_zero: The FatalNoise neverending story
Pompili - From hero to_zero: The FatalNoise neverending storyPompili - From hero to_zero: The FatalNoise neverending story
Pompili - From hero to_zero: The FatalNoise neverending story
 
Pastore - Commodore 65 - La storia
Pastore - Commodore 65 - La storiaPastore - Commodore 65 - La storia
Pastore - Commodore 65 - La storia
 
Pennisi - Essere Richard Altwasser
Pennisi - Essere Richard AltwasserPennisi - Essere Richard Altwasser
Pennisi - Essere Richard Altwasser
 
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
 
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
 
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
 
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Francesco Baldassarri  - Deliver Data at Scale - Codemotion Amsterdam 2019 - Francesco Baldassarri  - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 -
 
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
 
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
 
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
 
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
 
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
 
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
 
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
 
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
 
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
 
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
 
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
 
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
 

Recently uploaded

How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 

Recently uploaded (20)

How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 

Ddd cqrs - Forat Latif

  • 1. ROME 11-12 april 2014ROME 11-12 april 2014 Moving Away From CRUD: Domain Driven Design (DDD) and Command Query Responsibility Segregation (CQRS) Email: forat.latif@gmail.com Twitter: @foratlatif Forat Latif
  • 2. ROME 11-12 april 2014 - Speaker’s name Time to start a greenfield project
  • 3. ROME 11-12 april 2014 - Speaker’s name Process 1) Gather Requirements 2) Model our “Entities” 3) Scaffold our projects and our database based on those entities
  • 4. ROME 11-12 april 2014 - Speaker’s name What the Architecture looks like?
  • 5. ROME 11-12 april 2014 - Speaker’s name Our Domain class Product { String name; String description; Integer price; Integer discount; String category; } class Customer { Address address; String name; } class Order { String description; Customer customer; List<LineItems> lineItems; } class LineItem { Product product; }
  • 6. ROME 11-12 april 2014 - Speaker’s name Just what do we mean by Entity? class Product { String name; String description; Integer price; Integer discount; String category; String getDescription() { return this.description; } void setDescription(String aDescription) { this.description = aDescription; } String getName() { ……. …… }
  • 7. ROME 11-12 april 2014 - Speaker’s name So … Where is the business logic? class ProductService { public void discountProduct(String productId, Integer discount) { Product product = productRepository.find(productId); product.setDiscount(discount); if (discount > 30) { product.setStatus(“Super Discount”); } productRepository.save(aProduct); } }
  • 8. ROME 11-12 april 2014 - Speaker’s name So … Where is the business logic? class ProductController { public void updateProduct(Product product) { productRepository.save(product); } }
  • 9. ROME 11-12 april 2014 - Speaker’s name Are we really doing OOP? Objects are supposed to have a state and behavior that modifies that state State shouldn’t be exposed (getters and setters are not encapsulation) Objects should be loosely coupled Business rules should be placed in one place class Product { String name; String description; String category; String getName() { return this.description; } void setName(String name) { this.name= name; } String getPrice() { ……. …… }
  • 10. ROME 11-12 april 2014 - Speaker’s name Implicit Business Rules class PromoService { void discountProduct (String productId, Integer discount) { Product product = productRepository.find(productId); product.setDiscount(discount); if (discount > 30) { product.setStatus(“Super Discount”); } } } class AnotherService { void discountSomethinElse (String productId) { Product product = productRepository.find(productId); someValue = calculateValue(); product.setDiscount(someValue); } }
  • 11. ROME 11-12 april 2014 - Speaker’s name Objects should expose BEHAVIOR class Product { String name; String status; Integer price; Integer discount; String category; void discount(Integer discount) { this.discount = discount; if (discount > 30) { this.status = “Super Discount”; } } }
  • 12. ROME 11-12 april 2014 - Speaker’s name Back to our “Entities” class Customer { String name; Address address; } class Address { String street; Integer streetNumber; }
  • 13. ROME 11-12 april 2014 - Speaker’s name Entities and Value Objects Entities in DDD are not defined by their attributes, they are defined by a conceptual identity and we care about its changes Value Objects represent a description of something at a certain point in time. Thats why they are immutable and we care only about its attributes
  • 14. ROME 11-12 april 2014 - Speaker’s name What a purchase looks like class OrderService { @Transactional public void purchaseOrder(String orderId) { Order order = orderRepository .find(orderId); order.purchase(); productService.removeFromInventory(order.products()); emailService.sendConfirmationEmail(order); } }
  • 15. ROME 11-12 april 2014 - Speaker’s name Suddenly our mail server goes down …
  • 16. ROME 11-12 april 2014 - Forat Latif Domain Events A Domain Event, represents something that already happened, that is relevant to the business
  • 17. ROME 11-12 april 2014 - Forat Latif Domain Events class Service { void handle(SomeEvent event) { doSomething(); } }
  • 18. ROME 11-12 april 2014 - Forat Latif Domain Events class OrderService { @Transactional public void purchaseOrder(String orderId) { Order order = orderRepository .find(orderId); order.purchase(); productService.removeFromInventory(order.products()); eventBus.push(new OrderPurchased(order.orderId()); } } class EmailSender { public void handle(OrderPurchased orderPurchased) { Order order = orderRepository.find(orderPurchased.orderId); emailService.sendConfirmationEmail(order); } }
  • 19. ROME 11-12 april 2014 - Forat Latif Sales of a Product skyrocket ….
  • 20. ROME 11-12 april 2014 - Forat Latif Eventual Consistency class OrderService { @Transactional public void purchaseOrder(String orderId) { Order order = orderRepository .find(orderId); order.purchase(); eventBus.push(new OrderPurchased(order.orderId()); } } class OrderProcessManager { public void handle(OrderPurchased orderPurchased) { Order order = orderRepository.find(orderPurchased.orderId); productService.removeFromInventory(order.products()); } }
  • 21. ROME 11-12 april 2014 - Forat Latif Aggregate Roots Aggregate is a pattern in Domain-Driven Design. A DDD aggregate is a cluster of domain objects that can be treated as a single unit. An aggregate has a root that acts as an outside interface and keeps all invariants inside the aggregate. Each request should strive to load one aggregate and execute a single operation on it. Hence, Aggregates guarantee transactional consistency inside its boundaries
  • 22. ROME 11-12 april 2014 - Forat Latif What our new Architecture looks like
  • 23. ROME 11-12 april 2014 - Forat Latif Product Inventory and Catalog class Product { String name; Integer price; Integer priceFromSupplier; String supplier; String shippingStatus; String shippingMethod; }
  • 24. ROME 11-12 april 2014 - Forat Latif Bounded Contexts Explicitly define the context within which a model applies. Explicitly set boundaries in terms of team organization, usage within specific parts of the application, and physical manifestations such as code bases and database schemas. Keep the model strictly consistent within these bounds, but don’t be distracted or confused by issues outside. Inventory E-commerce Shipping
  • 25. ROME 11-12 april 2014 - Forat Latif Bounded Contexts class Product { String name; Integer price; } class Item { String shippingStatus; String shippingMethod; } class Product { Integer priceFromSupplier; String supplier; } E-Commerce Context Inventory Context Shipping Context
  • 26. ROME 11-12 april 2014 - Forat Latif Communication between BCs Inventory E-commerce Shipping
  • 27. ROME 11-12 april 2014 - Forat Latif How to identify BCs Ubiquitous Language Goals and Concerns Teams Organizational Structure
  • 28. ROME 11-12 april 2014 - Forat Latif So .. just what is DDD? Domain Driven Design is an approach to software development in which the Domain is the center of attention. - Strategic Design - Tactical Design We should focus on what matters, and thats adding value to our business through software, the software itself is just a byproduct of our strategy
  • 29. ROME 11-12 april 2014 - Forat Latif What about User Interfaces? class ProductController { Product viewProduct (String productId) { Product product = productRepository.find(productId); return product; } }
  • 30. ROME 11-12 april 2014 - Forat Latif User dashboard
  • 31. ROME 11-12 april 2014 - Forat Latif User Dashboard class ProductController { ProductDTO viewProduct (String productId) { //Solution 1: Do a manual query and map it to the DTO //Solution 2: Use your ORM to get all the objects you need // and map them to the DTO return productDTO; } }
  • 32. ROME 11-12 april 2014 - Forat Latif List the products of a category
  • 33. ROME 11-12 april 2014 - Forat Latif Category Tree
  • 34. ROME 11-12 april 2014 - Forat Latif Category Tree Model class Category { String name; Category parent; } class Product{ Category category; }
  • 35. ROME 11-12 april 2014 - Forat Latif “Simple” change request …
  • 36. ROME 11-12 april 2014 - Forat Latif Possible Solutions Nested Query: with CTQ as ( select * from Categories c where c.parentId = 1 union all select * from CTQ p, Categories c where c.parentId = p.categoryId ) select * from CTQ
  • 37. ROME 11-12 april 2014 - Forat Latif Possible Solutions Modify The domain: //Impedance Mismatch Pain class Category { List<Product> products; List<Category> children; } class Product { Category category; }
  • 38. ROME 11-12 april 2014 - Forat Latif Possible Solutions Another possibility: class Category { String parent1Id; String parent2Id; String parent3Id; …. String categoryId; String name; }
  • 39. ROME 11-12 april 2014 - Forat Latif Command Query Separation (CQS) Principle Command–query separation (CQS) is a principle that states that every method should either be a command that performs an action, or a query that returns data to the caller, but not both. In other words, asking a question should not change the answer Commands and Queries have different concerns
  • 40. ROME 11-12 april 2014 - Forat Latif Command Query Responsibility Segregation (CQRS) We can do CQS at the architectural level too ..... class CategoryReadService{ List<Categories> getChildrenCategories(String categoriId); } class CategoryWriteService{ void addCategory (String parendId, String name); }
  • 41. ROME 11-12 april 2014 - Forat Latif Command Query Responsibility Segregation (CQRS) where are do we need to do queries? when returning a DTO, not when performing a write operation when it comes to queries just query the database, why load a behavioral object to show data on a screen? You should modify your domain objects only when you need that change for write operations. If queries become too complex thats another sign that they are two different concerns
  • 42. ROME 11-12 april 2014 - Forat Latif Back to the User Dashboard
  • 43. ROME 11-12 april 2014 - Forat Latif User Dashboard with CQRS class UserDashboardProjector { handle(ProductAdded productAdded) { //insert into “user dashboard entry” with the data in the event } handle(ProductShipped productShipped) { //update “user dashboard entry” with the data in the event } } class ProductQueryProcessor { List<UserDashboardEntryDTO> getProducts(String userId) { //Select from “user dashboard entry” where userId = userId } }
  • 44. ROME 11-12 april 2014 - Forat Latif Category Tree with CQRS
  • 45. ROME 11-12 april 2014 - Forat Latif Category Tree with CQRS Books Technical Accademi c DDD Blue Book Some Weird Book Category Book Book Category
  • 46. ROME 11-12 april 2014 - Forat Latif Category Tree with CQRS class CategoryProjector { handle(CategoryAdded categoryAdded) { Vertex child = createVertex(); child.setProperty(“name”, categoryAdded.name()); Vertex parent = getVertex(categoryAdded.parentId()); parent.addEdge(child); } } class ProductQueryProcessor { List<ProductDTO> getProducts(String categoryId) { // graph query to get all children of type x; } }
  • 47. ROME 11-12 april 2014 - Forat Latif Multiple categories
  • 48. ROME 11-12 april 2014 - Forat Latif Multiple categories Without CQRS: Nested Query : …. Modify the domain (even more Impedance mismatch pain) Mixed: (join table unavoidable)
  • 49. ROME 11-12 april 2014 - Forat Latif Multiple categories With CQRS: class Product { List<Categories> categories; } and … thats it! The read model doesnt need to be modified
  • 50. ROME 11-12 april 2014 - Forat Latif Notice a pattern? Read model is data driven Write model is Domain Driven (database not important) To design your write model you can imagine that you dont need a database (you have infinite persisant RAM)
  • 51. ROME 11-12 april 2014 - Forat Latif Aggregates as Documents - consistency easier to maintain, - performance - scalability - technical simplicity (no lazy load config nor impedence mismatch) class Product { String productId; @EmbedSomehow // hopefully with a doc database List<String> categoryIds; }
  • 52. ROME 11-12 april 2014 - Forat Latif Commands class OrderService { @Transactional public void purchaseOrder(String orderId) { …… } } class PurchaseOrderCommandHandler { @Transactional public void handle(PurchaseOrderCommand command) { …… } }
  • 53. ROME 11-12 april 2014 - Forat Latif Advantages of Commands Command log (not your regular log) Clear user intention Improved Testability Integration Get rid of AOP Command Sourcing
  • 54. ROME 11-12 april 2014 - Forat Latif Advantages of Commands Represent an intention, which usually maps to a command method in your aggregate, which causes one or many events to be pushed. class ChangeCustomerTelephoneCommandHandler { @Transactional public void handle(ChangeCustomerTelephoneCommand command) { …… } }
  • 55. ROME 11-12 april 2014 - Forat Latif Overview of CQRS
  • 56. ROME 11-12 april 2014 - Forat Latif Recap of CQRS CQS is a principle that can be applied at the architecturale level. Read and Write are two separate concerns You cannot solve all problems with the same model, especially if the problem domains have different points of view
  • 57. ROME 11-12 april 2014ROME 11-12 april 2014 Moving Away From CRUD: Domain Driven Design (DDD) and Command Query Responsibility Segregation (CQRS) Forat Latif Email: forat.latif@gmail.com Twitter: @foratlatif Questions?