SlideShare uma empresa Scribd logo
1 de 43
Baixar para ler offline
Object Oriented Design
is mainly about
behaviour, not
structure.
2
What to ask when designing
0 Which class should a responsibility be assigned to?
0 How to organize the system’s responsibilities?
0 How to model the domain?
0 How to handle an object’s lifecycle?
0 How to prepare the code for modification?
3
Which class should a
responsibility be assigned to?
4
0Information Expert [GRASP]
0 A responsibility dealing with X should be
assigned to the object holding X
0Single Responsibility Principle [SOLID]
0 Each class should have one and only one
responsibility
0Interface Segregation [SOLID]
0 Favour small specific interfaces so clients don’t
depend on interfaces they don’t use
5
Corollary of Information Expert
Getters and setters are Evil
(don’t ask for data, delegate as much as possible)
6
Procedural thinking
7
Object thinking
8
How to organize the system’s
responsibilities?
9
Layers pattern
0 You are designing a system whose dominant
characteristic is a mix of low- and high-level issues,
where high-level operations rely on the lower-level
ones.
0 Therefore
0 Structure your system into an appropriate number of
layers and place them on top of each other, each
providing a specific level of abstraction.
10
GoF
Common architecture
Source: domain driven design , Eric Evans 11
0Low coupling [GRASP]
0 Keep coupling of elements to a minimum.
Avoid circular dependencies.
0High Cohesion [GRASP]
0 Keep related elements close together
0Indirection [GRASP]
0 Avoid tight coupling by creating an
indirection layer
13
Façade
0 Work is actually performed by a series of subsystem
but this level of complexity must be hidden from the
client
0 Therefore
0 Create a facade object offering a simpler, high level
interface which delegates work in the actual subsystems
14
GoF
Controller
0 You need to coordinate application activity - the
interactions of a use case with the UI or external
systems
0 Therefore
0 Assign the responsibility of use case coordination to a
dedicated use case controller which exposes a business
API (application layer) and performs no business logic
but delegates to the right domain objects instead
15
GRASP
How to model the domain?
16
Look at your domain model’s
ubiquitous language
17
Entity
0 Some objects in the domain have a thread of
continuity which we need to track by its identity.
0 Therefore
0 Model objects in the real world as entities, assigning
each object one or more identities. Equality of
references is done comparing the identity of the object.
18
DDD
Entity: example
Class Account{
public Account(AccountNumber accn) {…}
public boolean equals(Object other) {
if (other==this) return true;
if (!(other instanceof Account)) return false;
return (this.getID() == (Account)other.getID());
}
public void withdraw(Money amount) {
if (hasEnoughBalance(amount)
|| overdraftAllowed(amount)) {
// business logic for withdrawing
// and updating balances
}
}
}
19
Value Object
0 Not everything needs an identity; some things matter
for the value of its attributes.
0 Therefore
0 Create immutable objects whose equality is
determined by the equality of its attributes.
20
DDD
Value object: example
Class Balance{
public Balance(Money amount, Calendar asOf) {…}
// getters (but no setters)
public Money amount() {…}
public Calendar asOf() {…}
// creates a new Balance object
// keeping this and the other object unchanged
public Balance add(Money some) {…}
public Balance add(Money some, Calendar effectiveOn) {…}
public Balance subtract(Money some) {…}
...
public boolean equals(Object other) {…}
}
21
Service
0 Some business operations are not naturally placed
in a certain domain object
0 Therefore
0 Create a service object that handles only that operation
and coordinates the necessary domain objects.
23
DDD
Service: example
class TransferService {
public void transfer(Money amount,
Account from, Account to) {
if (isAllowedToTransfer(from, amount, to) {
from.withdraw(amount);
to.deposit(amount);
}
}
private boolean isAllowedToTransfer(Account from,
Money amount,
Account to) {
// rules specific to account transfers
// (e.g., maximum allowed amount to transfer for
// international account)
}
}
24
An Example
25
N-to-M
relationships
are hard
A pragmatic design
26
• 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...
Aggregate
0 Some objects are closely related together and we need
to control the scope of data changes so that invariants
are enforced
0 Therefore
0 Keep related objects with frequent changes bundled in
an aggregate
0 control access to the “inner” objects thru one single
“root” object
27
DDD
A more pragmatic design
28
Legend:
• Account
aggregate
• Customer
aggregate
Address is a value
object so it can be
freely shared among
several aggregates
How to handle an object’s
lifecycle?
29
Object’s lifecycle
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. …
30
Separate use from
construction
31
Factories
0 Creating a (large) object might be a complex task
and/or the client must be decoupled from the actual
type of the created object.
0 Therefore
0 Place construction logic in a dedicated factory which
encapsulates object creation for all clients.
32
DDD
0 Creator [GRASP]
0 Assign class A creation responsibility to the class which
either (1) contains A’s instances; or (2) holds the data
for initializing an A’s instance
0 Factory Method [GoF]
0 A class method that simplifies the creation of different
implementations of the same interface
0 Simple Factory [GoF]
0 A class made up of only factory methods
0 Abstract Factory [GoF]
0 Handles the creation of related or dependent product
families
33
Repository
0 Client code needs to obtain a reference to an object in
order to use it (sometimes, the desired object needs to
be reconstructed from persistence). After using it the
client wants the object to be persisted again.
0 Therefore
0 Encapsulate the logic needed for obtaining object
references in a Repository. The repository handles all
the persistence logic and abstracts the client code from
such details.
34
DDD
35
Repositoryexample
Repositories and layers
36
How to prepare the code for
modification?
37
Protected Variation
0 You need to design objects, components or systems so
that variations in those elements don’t impact other
elements
0 Therefore
0 Identify points of predicted variation and create a stable
interface around them.
38
GRASP
0Open/Close Principle [SOLID]
0 A class should be open for extension and
adaption and closed for modification
0Dependency Inversion Principle [SOLID]
0 Clients should depend on abstractions, not
concretions. I.e., program to an interface not
a realization.
39
0Polymorphism [GRASP]
0 When behaviour varies depending on type
0Template Method [GoF]
0 Define the skeleton of an algorithm in an
operation, deferring some steps to subclasses.
0Liskov Substitution Principle [SOLID]
0 Any method expecting A should work
properly with any object derived from A
40
Liskov Substitution Principle’s Corollary
Derived classes should adhere strictly to the semantics
of the contract
see also, Design by Contract:
Pre-conditions
Post-conditions
Invariants
41
Strategy
0 Sometimes there is a business policy (expressed in
the domain) that must be enforced but it actually may
have different variations of concrete policies
0 Therefore
0 Define a common interface for the policy and provide
different implementations decoupling the client from
the actual policy and allowing for permutation and
independent evolution.
42
GoF
Topic Principles and patterns
Which class should a responsibility be
assigned to?
Information Expert
Single Responsibility Principle
Interface Segregation Principle
How to organize the system’s
responsibilities?
Layers
Façade
Controller
How to model the domain? Entity
Value Object
Service
Aggregate
How to handle an object’s lifecycle? Factories
Repositories
How to prepare the code for
modification?
Protected Variation
Open/Close Principle
Dependency Inversion Principle
Liskov Substitution Principle
Template Method
Strategy
44
References
0 Domain Driven Design. Eric Evans
0 Why getters and setters are Evil. Allan Holub.
http://www.javaworld.com/article/2073723/core-
java/why-getter-and-setter-methods-are-evil.html
0 Design Principles and Design Patterns. Robert Martin.
http://www.objectmentor.com/resources/articles/Princip
les_and_Patterns.pdf
0 Design Patterns-Elements of Reusable Object-oriented
Software, Gamma et al. (Gang of Four)
0 Applying UML and Patterns; Craig Larman; (2nd ed.); 2002.
45

Mais conteúdo relacionado

Mais procurados

Design principles - SOLID
Design principles - SOLIDDesign principles - SOLID
Design principles - SOLIDPranalee Rokde
 
The SOLID Principles Illustrated by Design Patterns
The SOLID Principles Illustrated by Design PatternsThe SOLID Principles Illustrated by Design Patterns
The SOLID Principles Illustrated by Design PatternsHayim Makabee
 
PATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design PatternsPATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design PatternsMichael Heron
 
Software Design principles
Software Design principlesSoftware Design principles
Software Design principlesMilan Ashara
 
Introduction to Object oriented Design
Introduction to Object oriented DesignIntroduction to Object oriented Design
Introduction to Object oriented DesignAmin Shahnazari
 
Design patterns - Proxy & Composite
Design patterns - Proxy & CompositeDesign patterns - Proxy & Composite
Design patterns - Proxy & CompositeSarath C
 
Software Design Patterns. Part I :: Structural Patterns
Software Design Patterns. Part I :: Structural PatternsSoftware Design Patterns. Part I :: Structural Patterns
Software Design Patterns. Part I :: Structural PatternsSergey Aganezov
 
Null Object Design Pattern
Null Object Design PatternNull Object Design Pattern
Null Object Design Patterntcab22
 
Implications of Substitution
Implications of SubstitutionImplications of Substitution
Implications of Substitutionadil raja
 
Design Patterns
Design PatternsDesign Patterns
Design Patternssoms_1
 
Creational pattern
Creational patternCreational pattern
Creational patternHimanshu
 
Design patterns english
Design patterns englishDesign patterns english
Design patterns englishmeriem sari
 
Object Interconnections
Object InterconnectionsObject Interconnections
Object Interconnectionsadil raja
 
Software Architecture and Project Management module III : PATTERN OF ENTERPRISE
Software Architecture and Project Management module III : PATTERN OF ENTERPRISESoftware Architecture and Project Management module III : PATTERN OF ENTERPRISE
Software Architecture and Project Management module III : PATTERN OF ENTERPRISEsreeja_rajesh
 

Mais procurados (19)

Design principles - SOLID
Design principles - SOLIDDesign principles - SOLID
Design principles - SOLID
 
The SOLID Principles Illustrated by Design Patterns
The SOLID Principles Illustrated by Design PatternsThe SOLID Principles Illustrated by Design Patterns
The SOLID Principles Illustrated by Design Patterns
 
PATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design PatternsPATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design Patterns
 
Software Design principles
Software Design principlesSoftware Design principles
Software Design principles
 
Introduction to Object oriented Design
Introduction to Object oriented DesignIntroduction to Object oriented Design
Introduction to Object oriented Design
 
Input output
Input outputInput output
Input output
 
Object
ObjectObject
Object
 
Design patterns - Proxy & Composite
Design patterns - Proxy & CompositeDesign patterns - Proxy & Composite
Design patterns - Proxy & Composite
 
Software Design Patterns. Part I :: Structural Patterns
Software Design Patterns. Part I :: Structural PatternsSoftware Design Patterns. Part I :: Structural Patterns
Software Design Patterns. Part I :: Structural Patterns
 
Null Object Design Pattern
Null Object Design PatternNull Object Design Pattern
Null Object Design Pattern
 
Composite design pattern
Composite design patternComposite design pattern
Composite design pattern
 
Implications of Substitution
Implications of SubstitutionImplications of Substitution
Implications of Substitution
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Creational pattern
Creational patternCreational pattern
Creational pattern
 
Design patterns english
Design patterns englishDesign patterns english
Design patterns english
 
Object Interconnections
Object InterconnectionsObject Interconnections
Object Interconnections
 
Solid js
Solid jsSolid js
Solid js
 
Software Architecture and Project Management module III : PATTERN OF ENTERPRISE
Software Architecture and Project Management module III : PATTERN OF ENTERPRISESoftware Architecture and Project Management module III : PATTERN OF ENTERPRISE
Software Architecture and Project Management module III : PATTERN OF ENTERPRISE
 
Go f designpatterns 130116024923-phpapp02
Go f designpatterns 130116024923-phpapp02Go f designpatterns 130116024923-phpapp02
Go f designpatterns 130116024923-phpapp02
 

Destaque (14)

Principles of Service Orientation
Principles of Service OrientationPrinciples of Service Orientation
Principles of Service Orientation
 
Lição prova professor coordenador
Lição prova professor coordenadorLição prova professor coordenador
Lição prova professor coordenador
 
Patterns for distributed systems
Patterns for distributed systemsPatterns for distributed systems
Patterns for distributed systems
 
REST beyond CRUD
REST beyond CRUDREST beyond CRUD
REST beyond CRUD
 
Rest web services
Rest web servicesRest web services
Rest web services
 
PoEAA by Example
PoEAA by ExamplePoEAA by Example
PoEAA by Example
 
Modern web architectural patterns
Modern web architectural patternsModern web architectural patterns
Modern web architectural patterns
 
Enterprise Integration Patterns
Enterprise Integration PatternsEnterprise Integration Patterns
Enterprise Integration Patterns
 
Decoupled Communication
Decoupled CommunicationDecoupled Communication
Decoupled Communication
 
RESTful services Design Lab
RESTful services Design LabRESTful services Design Lab
RESTful services Design Lab
 
Communication
CommunicationCommunication
Communication
 
Benefits of Hypermedia API
Benefits of Hypermedia APIBenefits of Hypermedia API
Benefits of Hypermedia API
 
Software Product Lines
Software Product LinesSoftware Product Lines
Software Product Lines
 
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)
 

Semelhante a OO design principles and patterns

Test Driven Development (Delphi)
Test Driven Development (Delphi)Test Driven Development (Delphi)
Test Driven Development (Delphi)Alan Dean
 
Test Driven Development (C#)
Test Driven Development (C#)Test Driven Development (C#)
Test Driven Development (C#)Alan Dean
 
Domain Driven Design for Angular
Domain Driven Design for AngularDomain Driven Design for Angular
Domain Driven Design for AngularJennifer Estrada
 
Where i put my business logic - Greach 2014, Madrid, Spain
Where i put my business logic  - Greach 2014, Madrid, SpainWhere i put my business logic  - Greach 2014, Madrid, Spain
Where i put my business logic - Greach 2014, Madrid, SpainAntonio de la Torre Fernández
 
Orm and hibernate
Orm and hibernateOrm and hibernate
Orm and hibernates4al_com
 
Dependency injection Drupal Camp Wrocław 2014
Dependency injection Drupal Camp Wrocław 2014Dependency injection Drupal Camp Wrocław 2014
Dependency injection Drupal Camp Wrocław 2014Greg Szczotka
 
Identity Manager Opensource OpenIDM Architecture
Identity Manager Opensource OpenIDM ArchitectureIdentity Manager Opensource OpenIDM Architecture
Identity Manager Opensource OpenIDM ArchitectureAidy Tificate
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxanguraju1
 
Clean architecture: Android
Clean architecture: AndroidClean architecture: Android
Clean architecture: Androidintive
 
Oracle developer interview questions(entry level)
Oracle developer interview questions(entry level)Oracle developer interview questions(entry level)
Oracle developer interview questions(entry level)Naveen P
 
Combating software entropy 2-roc1-
Combating software entropy 2-roc1-Combating software entropy 2-roc1-
Combating software entropy 2-roc1-Hammad Rajjoub
 
Solid principles, Design Patterns, and Domain Driven Design
Solid principles, Design Patterns, and Domain Driven DesignSolid principles, Design Patterns, and Domain Driven Design
Solid principles, Design Patterns, and Domain Driven DesignIrwansyah Irwansyah
 
AngularJS 1.x - your first application (problems and solutions)
AngularJS 1.x - your first application (problems and solutions)AngularJS 1.x - your first application (problems and solutions)
AngularJS 1.x - your first application (problems and solutions)Igor Talevski
 

Semelhante a OO design principles and patterns (20)

Test Driven Development (Delphi)
Test Driven Development (Delphi)Test Driven Development (Delphi)
Test Driven Development (Delphi)
 
Test Driven Development (C#)
Test Driven Development (C#)Test Driven Development (C#)
Test Driven Development (C#)
 
Domain Driven Design for Angular
Domain Driven Design for AngularDomain Driven Design for Angular
Domain Driven Design for Angular
 
[iOS] Data Storage
[iOS] Data Storage[iOS] Data Storage
[iOS] Data Storage
 
Where i put my business logic - Greach 2014, Madrid, Spain
Where i put my business logic  - Greach 2014, Madrid, SpainWhere i put my business logic  - Greach 2014, Madrid, Spain
Where i put my business logic - Greach 2014, Madrid, Spain
 
Orm and hibernate
Orm and hibernateOrm and hibernate
Orm and hibernate
 
Best interview questions
Best interview questionsBest interview questions
Best interview questions
 
Dependency injection Drupal Camp Wrocław 2014
Dependency injection Drupal Camp Wrocław 2014Dependency injection Drupal Camp Wrocław 2014
Dependency injection Drupal Camp Wrocław 2014
 
Identity Manager Opensource OpenIDM Architecture
Identity Manager Opensource OpenIDM ArchitectureIdentity Manager Opensource OpenIDM Architecture
Identity Manager Opensource OpenIDM Architecture
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptx
 
Software Design principales
Software Design principalesSoftware Design principales
Software Design principales
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
 
Clean architecture: Android
Clean architecture: AndroidClean architecture: Android
Clean architecture: Android
 
L5 m256 block2_unit5
L5 m256 block2_unit5L5 m256 block2_unit5
L5 m256 block2_unit5
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Oracle developer interview questions(entry level)
Oracle developer interview questions(entry level)Oracle developer interview questions(entry level)
Oracle developer interview questions(entry level)
 
CS8592-OOAD Lecture Notes Unit-4
CS8592-OOAD Lecture Notes Unit-4CS8592-OOAD Lecture Notes Unit-4
CS8592-OOAD Lecture Notes Unit-4
 
Combating software entropy 2-roc1-
Combating software entropy 2-roc1-Combating software entropy 2-roc1-
Combating software entropy 2-roc1-
 
Solid principles, Design Patterns, and Domain Driven Design
Solid principles, Design Patterns, and Domain Driven DesignSolid principles, Design Patterns, and Domain Driven Design
Solid principles, Design Patterns, and Domain Driven Design
 
AngularJS 1.x - your first application (problems and solutions)
AngularJS 1.x - your first application (problems and solutions)AngularJS 1.x - your first application (problems and solutions)
AngularJS 1.x - your first application (problems and solutions)
 

Mais de Paulo Gandra de Sousa (9)

Introduction to Microservices
Introduction to MicroservicesIntroduction to Microservices
Introduction to Microservices
 
Minds-on DDD
Minds-on DDDMinds-on DDD
Minds-on DDD
 
Introduction to microservices
Introduction to microservicesIntroduction to microservices
Introduction to microservices
 
Design Patterns: Back to Basics
Design Patterns: Back to BasicsDesign Patterns: Back to Basics
Design Patterns: Back to Basics
 
Hypermedia APIs
Hypermedia APIsHypermedia APIs
Hypermedia APIs
 
Revision control with Mercurial
Revision control with MercurialRevision control with Mercurial
Revision control with Mercurial
 
Documenting Software Architectures
Documenting Software ArchitecturesDocumenting Software Architectures
Documenting Software Architectures
 
models of distributed computing
models of distributed computingmodels of distributed computing
models of distributed computing
 
Distributed Systems
Distributed SystemsDistributed Systems
Distributed Systems
 

Último

Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...OnePlan Solutions
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...Bert Jan Schrijver
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsJean Silva
 
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jGraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jNeo4j
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?Alexandre Beguel
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITmanoharjgpsolutions
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxRTS corp
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shardsChristopher Curtin
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptxVinzoCenzo
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingShane Coughlan
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...OnePlan Solutions
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxRTS corp
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingShane Coughlan
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfRTS corp
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogueitservices996
 
Zer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfZer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfmaor17
 

Último (20)

Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero results
 
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jGraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh IT
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptx
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogue
 
Zer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfZer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdf
 

OO design principles and patterns

  • 1.
  • 2. Object Oriented Design is mainly about behaviour, not structure. 2
  • 3. What to ask when designing 0 Which class should a responsibility be assigned to? 0 How to organize the system’s responsibilities? 0 How to model the domain? 0 How to handle an object’s lifecycle? 0 How to prepare the code for modification? 3
  • 4. Which class should a responsibility be assigned to? 4
  • 5. 0Information Expert [GRASP] 0 A responsibility dealing with X should be assigned to the object holding X 0Single Responsibility Principle [SOLID] 0 Each class should have one and only one responsibility 0Interface Segregation [SOLID] 0 Favour small specific interfaces so clients don’t depend on interfaces they don’t use 5
  • 6. Corollary of Information Expert Getters and setters are Evil (don’t ask for data, delegate as much as possible) 6
  • 9. How to organize the system’s responsibilities? 9
  • 10. Layers pattern 0 You are designing a system whose dominant characteristic is a mix of low- and high-level issues, where high-level operations rely on the lower-level ones. 0 Therefore 0 Structure your system into an appropriate number of layers and place them on top of each other, each providing a specific level of abstraction. 10 GoF
  • 11. Common architecture Source: domain driven design , Eric Evans 11
  • 12. 0Low coupling [GRASP] 0 Keep coupling of elements to a minimum. Avoid circular dependencies. 0High Cohesion [GRASP] 0 Keep related elements close together 0Indirection [GRASP] 0 Avoid tight coupling by creating an indirection layer 13
  • 13. Façade 0 Work is actually performed by a series of subsystem but this level of complexity must be hidden from the client 0 Therefore 0 Create a facade object offering a simpler, high level interface which delegates work in the actual subsystems 14 GoF
  • 14. Controller 0 You need to coordinate application activity - the interactions of a use case with the UI or external systems 0 Therefore 0 Assign the responsibility of use case coordination to a dedicated use case controller which exposes a business API (application layer) and performs no business logic but delegates to the right domain objects instead 15 GRASP
  • 15. How to model the domain? 16
  • 16. Look at your domain model’s ubiquitous language 17
  • 17. Entity 0 Some objects in the domain have a thread of continuity which we need to track by its identity. 0 Therefore 0 Model objects in the real world as entities, assigning each object one or more identities. Equality of references is done comparing the identity of the object. 18 DDD
  • 18. Entity: example Class Account{ public Account(AccountNumber accn) {…} public boolean equals(Object other) { if (other==this) return true; if (!(other instanceof Account)) return false; return (this.getID() == (Account)other.getID()); } public void withdraw(Money amount) { if (hasEnoughBalance(amount) || overdraftAllowed(amount)) { // business logic for withdrawing // and updating balances } } } 19
  • 19. Value Object 0 Not everything needs an identity; some things matter for the value of its attributes. 0 Therefore 0 Create immutable objects whose equality is determined by the equality of its attributes. 20 DDD
  • 20. Value object: example Class Balance{ public Balance(Money amount, Calendar asOf) {…} // getters (but no setters) public Money amount() {…} public Calendar asOf() {…} // creates a new Balance object // keeping this and the other object unchanged public Balance add(Money some) {…} public Balance add(Money some, Calendar effectiveOn) {…} public Balance subtract(Money some) {…} ... public boolean equals(Object other) {…} } 21
  • 21. Service 0 Some business operations are not naturally placed in a certain domain object 0 Therefore 0 Create a service object that handles only that operation and coordinates the necessary domain objects. 23 DDD
  • 22. Service: example class TransferService { public void transfer(Money amount, Account from, Account to) { if (isAllowedToTransfer(from, amount, to) { from.withdraw(amount); to.deposit(amount); } } private boolean isAllowedToTransfer(Account from, Money amount, Account to) { // rules specific to account transfers // (e.g., maximum allowed amount to transfer for // international account) } } 24
  • 24. A pragmatic design 26 • 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...
  • 25. Aggregate 0 Some objects are closely related together and we need to control the scope of data changes so that invariants are enforced 0 Therefore 0 Keep related objects with frequent changes bundled in an aggregate 0 control access to the “inner” objects thru one single “root” object 27 DDD
  • 26. A more pragmatic design 28 Legend: • Account aggregate • Customer aggregate Address is a value object so it can be freely shared among several aggregates
  • 27. How to handle an object’s lifecycle? 29
  • 28. Object’s lifecycle 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. … 30
  • 30. Factories 0 Creating a (large) object might be a complex task and/or the client must be decoupled from the actual type of the created object. 0 Therefore 0 Place construction logic in a dedicated factory which encapsulates object creation for all clients. 32 DDD
  • 31. 0 Creator [GRASP] 0 Assign class A creation responsibility to the class which either (1) contains A’s instances; or (2) holds the data for initializing an A’s instance 0 Factory Method [GoF] 0 A class method that simplifies the creation of different implementations of the same interface 0 Simple Factory [GoF] 0 A class made up of only factory methods 0 Abstract Factory [GoF] 0 Handles the creation of related or dependent product families 33
  • 32. Repository 0 Client code needs to obtain a reference to an object in order to use it (sometimes, the desired object needs to be reconstructed from persistence). After using it the client wants the object to be persisted again. 0 Therefore 0 Encapsulate the logic needed for obtaining object references in a Repository. The repository handles all the persistence logic and abstracts the client code from such details. 34 DDD
  • 35. How to prepare the code for modification? 37
  • 36. Protected Variation 0 You need to design objects, components or systems so that variations in those elements don’t impact other elements 0 Therefore 0 Identify points of predicted variation and create a stable interface around them. 38 GRASP
  • 37. 0Open/Close Principle [SOLID] 0 A class should be open for extension and adaption and closed for modification 0Dependency Inversion Principle [SOLID] 0 Clients should depend on abstractions, not concretions. I.e., program to an interface not a realization. 39
  • 38. 0Polymorphism [GRASP] 0 When behaviour varies depending on type 0Template Method [GoF] 0 Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. 0Liskov Substitution Principle [SOLID] 0 Any method expecting A should work properly with any object derived from A 40
  • 39. Liskov Substitution Principle’s Corollary Derived classes should adhere strictly to the semantics of the contract see also, Design by Contract: Pre-conditions Post-conditions Invariants 41
  • 40. Strategy 0 Sometimes there is a business policy (expressed in the domain) that must be enforced but it actually may have different variations of concrete policies 0 Therefore 0 Define a common interface for the policy and provide different implementations decoupling the client from the actual policy and allowing for permutation and independent evolution. 42 GoF
  • 41.
  • 42. Topic Principles and patterns Which class should a responsibility be assigned to? Information Expert Single Responsibility Principle Interface Segregation Principle How to organize the system’s responsibilities? Layers Façade Controller How to model the domain? Entity Value Object Service Aggregate How to handle an object’s lifecycle? Factories Repositories How to prepare the code for modification? Protected Variation Open/Close Principle Dependency Inversion Principle Liskov Substitution Principle Template Method Strategy 44
  • 43. References 0 Domain Driven Design. Eric Evans 0 Why getters and setters are Evil. Allan Holub. http://www.javaworld.com/article/2073723/core- java/why-getter-and-setter-methods-are-evil.html 0 Design Principles and Design Patterns. Robert Martin. http://www.objectmentor.com/resources/articles/Princip les_and_Patterns.pdf 0 Design Patterns-Elements of Reusable Object-oriented Software, Gamma et al. (Gang of Four) 0 Applying UML and Patterns; Craig Larman; (2nd ed.); 2002. 45