SlideShare a Scribd company logo
1 of 60
Paulo Gandra de Sousa
pag@isep.ipp.pt
Object-Oriented Design
is about behaviour,
not structure.
2
Procedural thinking where Objects are just Plain
data structures devoid of any behaviour, and
behaviour is concentrated in “service” and
“controller” classes.
3
4
 Bounded Context
 Entities
 Aggregate Roots
 Value Objects
“The fundamental assumption of
DDD is that human beings are
incapable of building enterprise
applications, but are capable of
understanding small, well-
bounded problems (a "domain").”
https://visualstudiomagazine.com/articles/2015/07/01/domain-
driven-design.aspx
5
6
7
First paradigm shift
8
 Problema:
 qual é o princípio geral para a atribuição de
responsabilidades aos objetos?
 Solução:
 Atribuir a responsabilidade ao information expert
- a classe que contém a informação necessária
para desempenhar essa responsabilidade
9
GRASP
class Employee {
private int number;
private double salary;
private List skil = new ArrayList();
...
public int getNumber() { … }
public void setNumber(int n) { … }
public double getSalary() { … }
public setSalary(double s) { … }
public List getSkills() { … }
public void setSkills(List s) { … }
}
10
Segregation of the design decisions that are most
likely to change, thus protecting other parts from
extensive modification if the design decision is
changed.
11
An object cannot be constructed neither modified
in a way that it does not hold its internal
consistency.
12
class Employee {
public Employee()
...
public void setNumber(int n) { … }
public setSalary(double s) { … }
public void setSkills(List s) { … }
}
 VS
class Employee {
public Employee(int number, double salary) { ... }
...
private void setNumber(int n) { … }
private void setSalary(double s) { … }
public void addSkill(Skill s) { … }
public void removeSkill(Skill s) { … }
}
13
 setFirstName(string fn)
 setLastName(string ln)
vs.
 changeName(
string first,
string last)
 setStatus(STATUS st)
 getStatus()
vs.
 activate()
 deactivate()
 isActive()
14
15
Procedural code gets
information then makes
decisions.
Object-oriented code tells
objects to do things.
— Alec Sharp
16
17
Second paradigm shift
18
One rule
19
 Objects wich rich behaviour in the real world
which we would like to track its identity
 Example:
 Student identified by Student Number, NIF,
email
 Product identified by Product Reference
 Sale identified by Invoice Number
20
DDD
Class Product{
private ProductID id;
// other attributes of product, e.g., designation,
description, etc.
public Product(String sku, Money price) {…}
public ProductID getProductID() { … }
private void setProductID(string sku) { … }
public boolean equals(Object other) {
if (other==this) return true;
if (!(other instanceof Product)) return false;
return (this.getProductID() ==
(Product)other.getProductID());
}
}
21
Always
constructed in a
valid state
It’s ok to return
one’s identity
No one can change
one’s identity
Object instances refers to
the same real world entity, if
they have the same identity
@Entity
Class Product{
// database ID
@ID
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private void setID(Long id) { … }
private Long getID() { … }
// domain ID
private ProductID ref;
public ProductID getProductID() { … }
private void setProductID(ProductID ref) { … }
…
}
22
 Problem
 Some objects matter for the value of its
attributes, e.g., Color
 Serve to describe, quantify or classify na Entity
 Solution
 Create immutable objects which are identified by
the equality of its attributes and do not need an
identity
24
DDD
class Color {
private final float red;
private final float green;
private final float blue;
public Color(int r, int g, int b) {…}
public float redPercentage() {…}
public float greenPercentage() {…}
public float bluePercentage() {…}
public boolean isPrimaryColor() {…}
// imutable; creates a new object
public Color combinedWith(Color other) {…}
// equality by value
public boolean equals(Object other) {…}
}
25
26
@Embeddable
class Color {
private int red;
private int green;
private int blue;
…
}
@Entity
Class Car {
…
private Color color;
…
}
27
@Entity
class Color {
// database ID not to be exposed to domain
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
// domain values
private int red;
private int green;
private int blue;
…
// avoid instantiation
private Color() {...}
//factory method
public static Color fromRGB(int r, int g, int b) { … }
}
@Entity
Class Car {
…
@OneToOne
private Color color;
…
}
Factory method hides
the lookup/write to the
DB if necessary.
The Domain, SRP and Value Objects
Primitive types are not the best option to represent
domain concepts!
Favour imutability of your objects.
28
Person
«value»
Name
«value»
Address
«value»
NIF
«value»
PhoneNumber
1..*1
1 *
«value»
Email
*
 Requirement 321:
 Passwords must be at least 6 characters longs and
have at least one digit
29
@Test
public void ensurePasswordHasAtLeastOneDigitAnd6CharactersLong() {
new Password("abcdefgh1");
}
@Test(expected = IllegalArgumentException.class)
public void ensurePasswordsSmallerThan6CharactersAreNotAllowed() {
new Password("ab1c");
}
@Test(expected = IllegalArgumentException.class)
public void ensurePasswordsWithoutDigitsAreNotAllowed() {
new Password("abcdefgh");
}
30
You are actually
doing design
@Test
public void ensurePasswordHasAtLeastOneDigitAnd6CharactersLong() {
Password p = Password.valueOf("abcdefgh1");
}
@Test(expected = IllegalArgumentException.class)
public void ensurePasswordsSmallerThan6CharactersAreNotAllowed() {
Password p = Password.valueOf("ab1c");
}
@Test(expected = IllegalArgumentException.class)
public void ensurePasswordsWithoutDigitsAreNotAllowed() {
Password p = Password.valueOf("abcdefgh");
}
31
Taking decisions on
how the code will
work
public class Password {
…
public Password(String password) {
if (!meetsMinimumRequirements(password)) {
throw new IllegalStateException();
}
thePassword = password;
}
private boolean meetsMinimumRequirements(String password) {
if (Strings.isNullOrEmpty(password)
|| password.length() < 6)
|| !Strings.containsDigit(password))
{
return false;
}
return true;
}
32
All methods of a domain object should handle
domain entities and value objects only; no primitive
types.
void setName(String name)
vs.
void setName(Name aName)
Provide a convenience valueOf() method to convert
from primitives read from the outside (e.g., UI, DB)
Class Name {
public static Name valueOf(String name) {…}
}
33
 Problem:
 Some business operations are not naturally
placed in a certain domain object
 Solution:
 Create a service object that handles only that
operation and coordinates the necessary domain
objects.
34
DDD
 Money transfer between two accounts:
Account.transferTo( Account other,
Money amount
)
vs.
TransferService.transfer( Money amount,
Account from,
Account to
)
35
DDD
36
1. An object is created
2. The object is used
3. It must be persisted for later use
4. Later, the object is reconstructed from
persistence
5. It is used (provably changed)
6. It is stored back again for later use
7. …
37
When creation of an entire, internally consistent
aggregate, or a large value object, becomes
complicated or reveals too much of the internal
structure, factories provide encapsulation.
38
DDD
 Problem:
 How to hide the details of persisting and
reconstructing an object while keeping the
domain language?
 Solution:
 Query access to aggregates expressed in the
ubiquitous language
 Abstract the persistence of an object in a
Repository class that behaves as a list
39
DDD
Another paradigm shift
40
41
N-to-M
relationships
are hard
42
• Remove
unnecessary
associations
• Force traversal
direction of
bidirectional
associations
• Reduce cardinality
by qualification of
the association
we are still left
with a tangle of
interconnected
objects...
 Some objects are closely related together
and we need to control the scope of data
changes so that invariants are enforced
 Therefore
 Keep related objects with frequent changes
bundled in an aggregate
 control access to the “inner” objects thru one
single “root” object
43
DDD
44
Legend:
• Account
aggregate
• Customer
aggregate
Address is a value
object so it can be
freely shared among
several aggregates
 Efficient aggregate design is hard
 Imagine the relationship between an account
and its movements
 Are movements part of the Account
aggregate?
45
Account
Movement
Account
Movement
Account Account
Movement
46
VS.
47
48
 Entities,Value objects and Aggregates are
about things
 Services are about operations
 But, what happens in the system is also
important.
 Some things that happen in the domain are
worth noting.
 Therefore
 Model activity in the domain as a series of
discrete events represented as a domain object.
49
DDD
 A domain event might be of interest to some
object.
 Therefore
 Make the interested object an observer of the
event’s issuing party.
50
GoF
51
fonte: Design Patterns: Elements of Reusable Object-Oriented Software
GoF
 A nice “global”Watchdog
 Event dispatcher
 Perfect for publish-subscribe technologies
 Specially for out of process observers
52
53
Aggregate X
«root»
X
«Entity»
Y
«Value»
A
«event»
E1
publishes
Aggregate V
«entity»
W
«Value»
D
«root»
V
«Value»
F
«service»
Watchdog/dispatcher
consumes
observes
Aggregate Z
observes
consumes
54
55
FormUI
-memberName
+OnOkClick()
UseCaseController
-memberName
+doUseCaseStep()
EntityFactory
-memberName
+create(): Entity
Entity
-memberName
-publishEvent(EntityEvent)
+doBusinessLogic()
«interface»
EntityRepository
+save(e: Entity)
SubEntity
-memberName
+doBusinessLogic()
RepositoryFactory
-memberName
+entityRepository()
SqlDbEntityRepository
+save(e: Entity)
EntityEvent
-memberName
+getState()
publishes
ObserverEntity
-memberName
+doBusinessLogic()
+onEventPublished(EntityEvent)
consumes
56
1. Getters and Setters are Evil
2. Entities, Value Objects
3. Aggregates, Domain Events
57
58https://blog.pragmatists.com/refactoring-from-anemic-model-to-ddd-880d3dd3d45f
 Anemic Domain Model, Martin Fowler.
http://martinfowler.com/bliki/AnemicDomain
Model.html
 Why getters and setters are Evil.Allan Holub.
http://www.javaworld.com/article/2073723/co
re-java/why-getter-and-setter-methods-are-
evil.html
 Tell, don’t ask.The Pragmatic Programmers.
https://pragprog.com/articles/tell-dont-ask
60
 Domain Driven Design (2004). Eric Evans
 Domain Driven Design reference (2011). Eric Evans.
http://domainlanguage.com/ddd/patterns/DDD_Refer
ence_2011-01-31.pdf
 Implementing Domain Driven Design (2013).Vernon
Vaughn.
 Services in Domain Driven Design (2008) Jimmy
Bogard.
http://lostechies.com/jimmybogard/2008/08/21/servic
es-in-domain-driven-design/
 Effective aggregate Design (2011)VernonVaughn.
http://dddcommunity.org/library/vernon_2011/
61
 Design Principles and Design Patterns.
Robert Martin.
http://www.objectmentor.com/resources/arti
cles/Principles_and_Patterns.pdf
 Applying UML and Patterns; Craig Larman;
(2nd ed.); 2002.
 Design Patterns-Elements of Reusable
Object-oriented Software, Gamma et al.
(Gang of Four)
62

More Related Content

What's hot

Approaching (almost) Any NLP Problem
Approaching (almost) Any NLP ProblemApproaching (almost) Any NLP Problem
Approaching (almost) Any NLP ProblemAbhishek Thakur
 
Structure & Union in C++
Structure & Union in C++Structure & Union in C++
Structure & Union in C++Davinder Kaur
 
Easy data-with-spring-data-jpa
Easy data-with-spring-data-jpaEasy data-with-spring-data-jpa
Easy data-with-spring-data-jpaStaples
 
Lecture09a computer applicationsie1_dratifshahzad
Lecture09a computer applicationsie1_dratifshahzadLecture09a computer applicationsie1_dratifshahzad
Lecture09a computer applicationsie1_dratifshahzadAtif Shahzad
 
04 sm3 xml_xp_07
04 sm3 xml_xp_0704 sm3 xml_xp_07
04 sm3 xml_xp_07Niit Care
 
03 sm3 xml_xp_06
03 sm3 xml_xp_0603 sm3 xml_xp_06
03 sm3 xml_xp_06Niit Care
 
Dev Cast Dependency Injection
Dev Cast Dependency InjectionDev Cast Dependency Injection
Dev Cast Dependency InjectionDylan Thomas
 
重構—改善既有程式的設計(chapter 8)part 1
重構—改善既有程式的設計(chapter 8)part 1重構—改善既有程式的設計(chapter 8)part 1
重構—改善既有程式的設計(chapter 8)part 1Chris Huang
 
Spring data presentation
Spring data presentationSpring data presentation
Spring data presentationOleksii Usyk
 
C++ programming structure & union
C++ programming structure & unionC++ programming structure & union
C++ programming structure & unionargusacademy
 
object oriented programming language by c++
object oriented programming language by c++object oriented programming language by c++
object oriented programming language by c++Mohamad Al_hsan
 
Intake 38 data access 5
Intake 38 data access 5Intake 38 data access 5
Intake 38 data access 5Mahmoud Ouf
 
Cs1123 12 structures
Cs1123 12 structuresCs1123 12 structures
Cs1123 12 structuresTAlha MAlik
 
Intake 38 data access 3
Intake 38 data access 3Intake 38 data access 3
Intake 38 data access 3Mahmoud Ouf
 
重構—改善既有程式的設計(chapter 8)part 2
重構—改善既有程式的設計(chapter 8)part 2重構—改善既有程式的設計(chapter 8)part 2
重構—改善既有程式的設計(chapter 8)part 2Chris Huang
 
Lecture 2 - Classes, Fields, Parameters, Methods and Constructors
Lecture 2 - Classes, Fields, Parameters, Methods and ConstructorsLecture 2 - Classes, Fields, Parameters, Methods and Constructors
Lecture 2 - Classes, Fields, Parameters, Methods and ConstructorsSyed Afaq Shah MACS CP
 

What's hot (20)

Approaching (almost) Any NLP Problem
Approaching (almost) Any NLP ProblemApproaching (almost) Any NLP Problem
Approaching (almost) Any NLP Problem
 
Java Persistence API
Java Persistence APIJava Persistence API
Java Persistence API
 
Structure & Union in C++
Structure & Union in C++Structure & Union in C++
Structure & Union in C++
 
Easy data-with-spring-data-jpa
Easy data-with-spring-data-jpaEasy data-with-spring-data-jpa
Easy data-with-spring-data-jpa
 
Lecture09a computer applicationsie1_dratifshahzad
Lecture09a computer applicationsie1_dratifshahzadLecture09a computer applicationsie1_dratifshahzad
Lecture09a computer applicationsie1_dratifshahzad
 
04 sm3 xml_xp_07
04 sm3 xml_xp_0704 sm3 xml_xp_07
04 sm3 xml_xp_07
 
03 sm3 xml_xp_06
03 sm3 xml_xp_0603 sm3 xml_xp_06
03 sm3 xml_xp_06
 
Dev Cast Dependency Injection
Dev Cast Dependency InjectionDev Cast Dependency Injection
Dev Cast Dependency Injection
 
Object-oriented Basics
Object-oriented BasicsObject-oriented Basics
Object-oriented Basics
 
重構—改善既有程式的設計(chapter 8)part 1
重構—改善既有程式的設計(chapter 8)part 1重構—改善既有程式的設計(chapter 8)part 1
重構—改善既有程式的設計(chapter 8)part 1
 
Spring data presentation
Spring data presentationSpring data presentation
Spring data presentation
 
C++ programming structure & union
C++ programming structure & unionC++ programming structure & union
C++ programming structure & union
 
object oriented programming language by c++
object oriented programming language by c++object oriented programming language by c++
object oriented programming language by c++
 
Intake 38 data access 5
Intake 38 data access 5Intake 38 data access 5
Intake 38 data access 5
 
Cs1123 12 structures
Cs1123 12 structuresCs1123 12 structures
Cs1123 12 structures
 
Intake 38 data access 3
Intake 38 data access 3Intake 38 data access 3
Intake 38 data access 3
 
重構—改善既有程式的設計(chapter 8)part 2
重構—改善既有程式的設計(chapter 8)part 2重構—改善既有程式的設計(chapter 8)part 2
重構—改善既有程式的設計(chapter 8)part 2
 
Neo4 j
Neo4 jNeo4 j
Neo4 j
 
Lecture 2 - Classes, Fields, Parameters, Methods and Constructors
Lecture 2 - Classes, Fields, Parameters, Methods and ConstructorsLecture 2 - Classes, Fields, Parameters, Methods and Constructors
Lecture 2 - Classes, Fields, Parameters, Methods and Constructors
 
Structures
StructuresStructures
Structures
 

Similar to Object-Oriented Design is about Behaviour

Pursuing Domain-Driven Design practices in PHP
Pursuing Domain-Driven Design practices in PHPPursuing Domain-Driven Design practices in PHP
Pursuing Domain-Driven Design practices in PHPGiorgio Sironi
 
NoSQL Endgame DevoxxUA Conference 2020
NoSQL Endgame DevoxxUA Conference 2020NoSQL Endgame DevoxxUA Conference 2020
NoSQL Endgame DevoxxUA Conference 2020Thodoris Bais
 
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019Victor Rentea
 
03 Object Relational Mapping
03 Object Relational Mapping03 Object Relational Mapping
03 Object Relational MappingRanjan Kumar
 
Pursuing practices of Domain-Driven Design in PHP
Pursuing practices of Domain-Driven Design in PHPPursuing practices of Domain-Driven Design in PHP
Pursuing practices of Domain-Driven Design in PHPGiorgio Sironi
 
NoSQL Endgame Percona Live Online 2020
NoSQL Endgame Percona Live Online 2020NoSQL Endgame Percona Live Online 2020
NoSQL Endgame Percona Live Online 2020Thodoris Bais
 
Paintfree Object-Document Mapping for MongoDB by Philipp Krenn
Paintfree Object-Document Mapping for MongoDB by Philipp KrennPaintfree Object-Document Mapping for MongoDB by Philipp Krenn
Paintfree Object-Document Mapping for MongoDB by Philipp KrennJavaDayUA
 
ADBMS ASSIGNMENT
ADBMS ASSIGNMENTADBMS ASSIGNMENT
ADBMS ASSIGNMENTLori Moore
 
Compiler Case Study - Design Patterns in C#
Compiler Case Study - Design Patterns in C#Compiler Case Study - Design Patterns in C#
Compiler Case Study - Design Patterns in C#CodeOps Technologies LLP
 
Ch.1 oop introduction, classes and objects
Ch.1 oop introduction, classes and objectsCh.1 oop introduction, classes and objects
Ch.1 oop introduction, classes and objectsITNet
 
CSharp presentation and software developement
CSharp presentation and software developementCSharp presentation and software developement
CSharp presentation and software developementfrwebhelp
 
Scala the good and bad parts
Scala the good and bad partsScala the good and bad parts
Scala the good and bad partsbenewu
 
Practices For Becoming A Better Programmer
Practices For Becoming A Better ProgrammerPractices For Becoming A Better Programmer
Practices For Becoming A Better ProgrammerSrikanth Shreenivas
 
Introduction to-csharp
Introduction to-csharpIntroduction to-csharp
Introduction to-csharpSDFG5
 
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...Introduction to Csharp (C-Sharp) is a programming language developed by Micro...
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...NALESVPMEngg
 
Introduction-to-Csharp.ppt
Introduction-to-Csharp.pptIntroduction-to-Csharp.ppt
Introduction-to-Csharp.pptAlmamoon
 

Similar to Object-Oriented Design is about Behaviour (20)

Pursuing Domain-Driven Design practices in PHP
Pursuing Domain-Driven Design practices in PHPPursuing Domain-Driven Design practices in PHP
Pursuing Domain-Driven Design practices in PHP
 
NoSQL Endgame DevoxxUA Conference 2020
NoSQL Endgame DevoxxUA Conference 2020NoSQL Endgame DevoxxUA Conference 2020
NoSQL Endgame DevoxxUA Conference 2020
 
Clean Code 2
Clean Code 2Clean Code 2
Clean Code 2
 
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
 
03 Object Relational Mapping
03 Object Relational Mapping03 Object Relational Mapping
03 Object Relational Mapping
 
Pursuing practices of Domain-Driven Design in PHP
Pursuing practices of Domain-Driven Design in PHPPursuing practices of Domain-Driven Design in PHP
Pursuing practices of Domain-Driven Design in PHP
 
34. uml
34. uml34. uml
34. uml
 
NoSQL Endgame Percona Live Online 2020
NoSQL Endgame Percona Live Online 2020NoSQL Endgame Percona Live Online 2020
NoSQL Endgame Percona Live Online 2020
 
Paintfree Object-Document Mapping for MongoDB by Philipp Krenn
Paintfree Object-Document Mapping for MongoDB by Philipp KrennPaintfree Object-Document Mapping for MongoDB by Philipp Krenn
Paintfree Object-Document Mapping for MongoDB by Philipp Krenn
 
ADBMS ASSIGNMENT
ADBMS ASSIGNMENTADBMS ASSIGNMENT
ADBMS ASSIGNMENT
 
Compiler Case Study - Design Patterns in C#
Compiler Case Study - Design Patterns in C#Compiler Case Study - Design Patterns in C#
Compiler Case Study - Design Patterns in C#
 
Ch.1 oop introduction, classes and objects
Ch.1 oop introduction, classes and objectsCh.1 oop introduction, classes and objects
Ch.1 oop introduction, classes and objects
 
CSharp presentation and software developement
CSharp presentation and software developementCSharp presentation and software developement
CSharp presentation and software developement
 
Scala the good and bad parts
Scala the good and bad partsScala the good and bad parts
Scala the good and bad parts
 
Green dao
Green daoGreen dao
Green dao
 
Practices For Becoming A Better Programmer
Practices For Becoming A Better ProgrammerPractices For Becoming A Better Programmer
Practices For Becoming A Better Programmer
 
Advance oops concepts
Advance oops conceptsAdvance oops concepts
Advance oops concepts
 
Introduction to-csharp
Introduction to-csharpIntroduction to-csharp
Introduction to-csharp
 
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...Introduction to Csharp (C-Sharp) is a programming language developed by Micro...
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...
 
Introduction-to-Csharp.ppt
Introduction-to-Csharp.pptIntroduction-to-Csharp.ppt
Introduction-to-Csharp.ppt
 

More from Paulo Gandra de Sousa

Design Patterns: From STUPID to SOLID code
Design Patterns: From STUPID to SOLID codeDesign Patterns: From STUPID to SOLID code
Design Patterns: From STUPID to SOLID codePaulo Gandra de Sousa
 
Patterns of Enterprise Application Architecture (by example)
Patterns of Enterprise Application Architecture (by example)Patterns of Enterprise Application Architecture (by example)
Patterns of Enterprise Application Architecture (by example)Paulo Gandra de Sousa
 

More from Paulo Gandra de Sousa (20)

Introduction to Microservices
Introduction to MicroservicesIntroduction to Microservices
Introduction to Microservices
 
Introduction to microservices
Introduction to microservicesIntroduction to microservices
Introduction to microservices
 
Benefits of Hypermedia API
Benefits of Hypermedia APIBenefits of Hypermedia API
Benefits of Hypermedia API
 
Design Patterns: From STUPID to SOLID code
Design Patterns: From STUPID to SOLID codeDesign Patterns: From STUPID to SOLID code
Design Patterns: From STUPID to SOLID code
 
Hypermedia APIs
Hypermedia APIsHypermedia APIs
Hypermedia APIs
 
RESTful services Design Lab
RESTful services Design LabRESTful services Design Lab
RESTful services Design Lab
 
Principles of Service Orientation
Principles of Service OrientationPrinciples of Service Orientation
Principles of Service Orientation
 
OO design principles and patterns
OO design principles and patternsOO design principles and patterns
OO design principles and patterns
 
Modern web architectural patterns
Modern web architectural patternsModern web architectural patterns
Modern web architectural patterns
 
REST beyond CRUD
REST beyond CRUDREST beyond CRUD
REST beyond CRUD
 
Revision control with Mercurial
Revision control with MercurialRevision control with Mercurial
Revision control with Mercurial
 
Rest web services
Rest web servicesRest web services
Rest web services
 
Lição prova professor coordenador
Lição prova professor coordenadorLição prova professor coordenador
Lição prova professor coordenador
 
Documenting Software Architectures
Documenting Software ArchitecturesDocumenting Software Architectures
Documenting Software Architectures
 
Patterns of Enterprise Application Architecture (by example)
Patterns of Enterprise Application Architecture (by example)Patterns of Enterprise Application Architecture (by example)
Patterns of Enterprise Application Architecture (by example)
 
Software Product Lines
Software Product LinesSoftware Product Lines
Software Product Lines
 
Enterprise Integration Patterns
Enterprise Integration PatternsEnterprise Integration Patterns
Enterprise Integration Patterns
 
Patterns for distributed systems
Patterns for distributed systemsPatterns for distributed systems
Patterns for distributed systems
 
Decoupled Communication
Decoupled CommunicationDecoupled Communication
Decoupled Communication
 
Communication
CommunicationCommunication
Communication
 

Recently uploaded

A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 

Recently uploaded (20)

A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 

Object-Oriented Design is about Behaviour

  • 1. Paulo Gandra de Sousa pag@isep.ipp.pt
  • 2. Object-Oriented Design is about behaviour, not structure. 2
  • 3. Procedural thinking where Objects are just Plain data structures devoid of any behaviour, and behaviour is concentrated in “service” and “controller” classes. 3
  • 4. 4  Bounded Context  Entities  Aggregate Roots  Value Objects
  • 5. “The fundamental assumption of DDD is that human beings are incapable of building enterprise applications, but are capable of understanding small, well- bounded problems (a "domain").” https://visualstudiomagazine.com/articles/2015/07/01/domain- driven-design.aspx 5
  • 6. 6
  • 7. 7
  • 9.  Problema:  qual é o princípio geral para a atribuição de responsabilidades aos objetos?  Solução:  Atribuir a responsabilidade ao information expert - a classe que contém a informação necessária para desempenhar essa responsabilidade 9 GRASP
  • 10. class Employee { private int number; private double salary; private List skil = new ArrayList(); ... public int getNumber() { … } public void setNumber(int n) { … } public double getSalary() { … } public setSalary(double s) { … } public List getSkills() { … } public void setSkills(List s) { … } } 10
  • 11. Segregation of the design decisions that are most likely to change, thus protecting other parts from extensive modification if the design decision is changed. 11
  • 12. An object cannot be constructed neither modified in a way that it does not hold its internal consistency. 12
  • 13. class Employee { public Employee() ... public void setNumber(int n) { … } public setSalary(double s) { … } public void setSkills(List s) { … } }  VS class Employee { public Employee(int number, double salary) { ... } ... private void setNumber(int n) { … } private void setSalary(double s) { … } public void addSkill(Skill s) { … } public void removeSkill(Skill s) { … } } 13
  • 14.  setFirstName(string fn)  setLastName(string ln) vs.  changeName( string first, string last)  setStatus(STATUS st)  getStatus() vs.  activate()  deactivate()  isActive() 14
  • 15. 15 Procedural code gets information then makes decisions. Object-oriented code tells objects to do things. — Alec Sharp
  • 16. 16
  • 17. 17
  • 20.  Objects wich rich behaviour in the real world which we would like to track its identity  Example:  Student identified by Student Number, NIF, email  Product identified by Product Reference  Sale identified by Invoice Number 20 DDD
  • 21. Class Product{ private ProductID id; // other attributes of product, e.g., designation, description, etc. public Product(String sku, Money price) {…} public ProductID getProductID() { … } private void setProductID(string sku) { … } public boolean equals(Object other) { if (other==this) return true; if (!(other instanceof Product)) return false; return (this.getProductID() == (Product)other.getProductID()); } } 21 Always constructed in a valid state It’s ok to return one’s identity No one can change one’s identity Object instances refers to the same real world entity, if they have the same identity
  • 22. @Entity Class Product{ // database ID @ID @GeneratedValue(strategy=GenerationType.AUTO) private Long id; private void setID(Long id) { … } private Long getID() { … } // domain ID private ProductID ref; public ProductID getProductID() { … } private void setProductID(ProductID ref) { … } … } 22
  • 23.  Problem  Some objects matter for the value of its attributes, e.g., Color  Serve to describe, quantify or classify na Entity  Solution  Create immutable objects which are identified by the equality of its attributes and do not need an identity 24 DDD
  • 24. class Color { private final float red; private final float green; private final float blue; public Color(int r, int g, int b) {…} public float redPercentage() {…} public float greenPercentage() {…} public float bluePercentage() {…} public boolean isPrimaryColor() {…} // imutable; creates a new object public Color combinedWith(Color other) {…} // equality by value public boolean equals(Object other) {…} } 25
  • 25. 26 @Embeddable class Color { private int red; private int green; private int blue; … } @Entity Class Car { … private Color color; … }
  • 26. 27 @Entity class Color { // database ID not to be exposed to domain @Id @GeneratedValue(strategy=GenerationType.AUTO) private int id; // domain values private int red; private int green; private int blue; … // avoid instantiation private Color() {...} //factory method public static Color fromRGB(int r, int g, int b) { … } } @Entity Class Car { … @OneToOne private Color color; … } Factory method hides the lookup/write to the DB if necessary.
  • 27. The Domain, SRP and Value Objects Primitive types are not the best option to represent domain concepts! Favour imutability of your objects. 28 Person «value» Name «value» Address «value» NIF «value» PhoneNumber 1..*1 1 * «value» Email *
  • 28.  Requirement 321:  Passwords must be at least 6 characters longs and have at least one digit 29
  • 29. @Test public void ensurePasswordHasAtLeastOneDigitAnd6CharactersLong() { new Password("abcdefgh1"); } @Test(expected = IllegalArgumentException.class) public void ensurePasswordsSmallerThan6CharactersAreNotAllowed() { new Password("ab1c"); } @Test(expected = IllegalArgumentException.class) public void ensurePasswordsWithoutDigitsAreNotAllowed() { new Password("abcdefgh"); } 30 You are actually doing design
  • 30. @Test public void ensurePasswordHasAtLeastOneDigitAnd6CharactersLong() { Password p = Password.valueOf("abcdefgh1"); } @Test(expected = IllegalArgumentException.class) public void ensurePasswordsSmallerThan6CharactersAreNotAllowed() { Password p = Password.valueOf("ab1c"); } @Test(expected = IllegalArgumentException.class) public void ensurePasswordsWithoutDigitsAreNotAllowed() { Password p = Password.valueOf("abcdefgh"); } 31 Taking decisions on how the code will work
  • 31. public class Password { … public Password(String password) { if (!meetsMinimumRequirements(password)) { throw new IllegalStateException(); } thePassword = password; } private boolean meetsMinimumRequirements(String password) { if (Strings.isNullOrEmpty(password) || password.length() < 6) || !Strings.containsDigit(password)) { return false; } return true; } 32
  • 32. All methods of a domain object should handle domain entities and value objects only; no primitive types. void setName(String name) vs. void setName(Name aName) Provide a convenience valueOf() method to convert from primitives read from the outside (e.g., UI, DB) Class Name { public static Name valueOf(String name) {…} } 33
  • 33.  Problem:  Some business operations are not naturally placed in a certain domain object  Solution:  Create a service object that handles only that operation and coordinates the necessary domain objects. 34 DDD
  • 34.  Money transfer between two accounts: Account.transferTo( Account other, Money amount ) vs. TransferService.transfer( Money amount, Account from, Account to ) 35 DDD
  • 35. 36
  • 36. 1. An object is created 2. The object is used 3. It must be persisted for later use 4. Later, the object is reconstructed from persistence 5. It is used (provably changed) 6. It is stored back again for later use 7. … 37
  • 37. When creation of an entire, internally consistent aggregate, or a large value object, becomes complicated or reveals too much of the internal structure, factories provide encapsulation. 38 DDD
  • 38.  Problem:  How to hide the details of persisting and reconstructing an object while keeping the domain language?  Solution:  Query access to aggregates expressed in the ubiquitous language  Abstract the persistence of an object in a Repository class that behaves as a list 39 DDD
  • 41. 42 • Remove unnecessary associations • Force traversal direction of bidirectional associations • Reduce cardinality by qualification of the association we are still left with a tangle of interconnected objects...
  • 42.  Some objects are closely related together and we need to control the scope of data changes so that invariants are enforced  Therefore  Keep related objects with frequent changes bundled in an aggregate  control access to the “inner” objects thru one single “root” object 43 DDD
  • 43. 44 Legend: • Account aggregate • Customer aggregate Address is a value object so it can be freely shared among several aggregates
  • 44.  Efficient aggregate design is hard  Imagine the relationship between an account and its movements  Are movements part of the Account aggregate? 45
  • 46. 47
  • 47. 48  Entities,Value objects and Aggregates are about things  Services are about operations  But, what happens in the system is also important.
  • 48.  Some things that happen in the domain are worth noting.  Therefore  Model activity in the domain as a series of discrete events represented as a domain object. 49 DDD
  • 49.  A domain event might be of interest to some object.  Therefore  Make the interested object an observer of the event’s issuing party. 50 GoF
  • 50. 51 fonte: Design Patterns: Elements of Reusable Object-Oriented Software GoF
  • 51.  A nice “global”Watchdog  Event dispatcher  Perfect for publish-subscribe technologies  Specially for out of process observers 52
  • 53. 54
  • 55. 56
  • 56. 1. Getters and Setters are Evil 2. Entities, Value Objects 3. Aggregates, Domain Events 57
  • 58.  Anemic Domain Model, Martin Fowler. http://martinfowler.com/bliki/AnemicDomain Model.html  Why getters and setters are Evil.Allan Holub. http://www.javaworld.com/article/2073723/co re-java/why-getter-and-setter-methods-are- evil.html  Tell, don’t ask.The Pragmatic Programmers. https://pragprog.com/articles/tell-dont-ask 60
  • 59.  Domain Driven Design (2004). Eric Evans  Domain Driven Design reference (2011). Eric Evans. http://domainlanguage.com/ddd/patterns/DDD_Refer ence_2011-01-31.pdf  Implementing Domain Driven Design (2013).Vernon Vaughn.  Services in Domain Driven Design (2008) Jimmy Bogard. http://lostechies.com/jimmybogard/2008/08/21/servic es-in-domain-driven-design/  Effective aggregate Design (2011)VernonVaughn. http://dddcommunity.org/library/vernon_2011/ 61
  • 60.  Design Principles and Design Patterns. Robert Martin. http://www.objectmentor.com/resources/arti cles/Principles_and_Patterns.pdf  Applying UML and Patterns; Craig Larman; (2nd ed.); 2002.  Design Patterns-Elements of Reusable Object-oriented Software, Gamma et al. (Gang of Four) 62

Editor's Notes

  1. The hollyhood principle: don’t call us, we’ll call you After all it is called OBJECT-oriented and not CLASS-oriented
  2. Source: implementing DDD, Vernon Vaugh
  3. Breaks encapsulation Breaks information hiding Variation points are not protected, e.g., employee “number” might be a string, or we may want to use LinkedList instead of ArrayList but we can’t without extensive change to the codebase. Se um objeto é o information expert de um dado tópico (informação), não tem nada que dar essa informação a outras para que esses outros façam “as contas”
  4. The protection involves providing a stable interface which protects the remainder of the program from the implementation (the details that are most likely to change). Information expert Getters and setters are evil Construct objects only in avalid state
  5. Beware of empty constructors and atomic setters when things need to change in clusters
  6. Intention Revealing Interface
  7. Os objetos são preguiçosos: fazem o mínimo possível e delegam o máximo possível
  8. https://www.websequencediagrams.com title calculating the total for an order (procedural) App -> Order : getPrice() loop for each item Order->OrderItem: getQuantity() Order->OrderItem: getProduct() Order->Product:getPrice() Order->Order: sum() end
  9. https://www.websequencediagrams.com title calculating the total for an order (Object Orientation) App -> Order : getPrice() loop for each item Order->OrderItem: getPrice() OrderItem->Product:getPrice(quantity) Order->Order: sum() end
  10. Método equals para verificação de igualdade (e não identidade) Existência de vários concstrutores Vários métodos de “query” mas nenhum de “comand” (mutators) Operações não alteram o conteudo deste objecto mas sim retornnam novos objectos -- ver método combinedWith -- reparar no nome do método: “combined” e não “combine”
  11. Método equals para verificação de igualdade (e não identidade) Existência de vários construtores Vários métodos de “query” mas nenhum de “command” (mutators) Operações não alteram o conteúdo deste objeto mas sim retornam novos objetos -- ver método combinedWith -- reparar no nome do método: “combined” e não “combine”
  12. Still need to hold to all value objects characteristics: imutability, … Factory methods might be in the Repository class
  13. Extrato faltam aqui alguns métodos. Devem ver o código fonte completo
  14. After reducing and simplifying associations we are still left with a tangle of interconnected objects.
  15. Other objects are not allowed to have references to “inner” objects of an agregate, only to its root
  16. The model must be practical
  17. they can serve as a trace to what have happed, why an entity is in a specific state, or other objects might be interested to perform some other action. Events should have meaningfull names based o the domain
  18. Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically
  19. “Global” event listener
  20. note left of O: subscribe to future events O -> +Dispatcher: subscribe(eventType) Dispatcher --> -O: note over Ctrl, P: during program execution Ctrl -> +P : func() P -> P : ... P -> *e Event: create P -> Dispatcher:publish(e) P --> -Ctrl: note left of Dispatcher: asynchronously notify subscribers Dispatcher -> O: handle(e)