SlideShare a Scribd company logo
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

More Related Content

What's hot

Design principles - SOLID
Design principles - SOLIDDesign principles - SOLID
Design principles - SOLID
Pranalee 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 Patterns
Hayim Makabee
 
PATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design PatternsPATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design Patterns
Michael Heron
 
Software Design principles
Software Design principlesSoftware Design principles
Software Design principles
Milan Ashara
 
Introduction to Object oriented Design
Introduction to Object oriented DesignIntroduction to Object oriented Design
Introduction to Object oriented Design
Amin Shahnazari
 
Object
ObjectObject
Design patterns - Proxy & Composite
Design patterns - Proxy & CompositeDesign patterns - Proxy & Composite
Design patterns - Proxy & Composite
Sarath 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 Patterns
Sergey Aganezov
 
Null Object Design Pattern
Null Object Design PatternNull Object Design Pattern
Null Object Design Pattern
tcab22
 
Composite design pattern
Composite design patternComposite design pattern
Composite design pattern
MUHAMMAD FARHAN ASLAM
 
Implications of Substitution
Implications of SubstitutionImplications of Substitution
Implications of Substitution
adil raja
 
Design Patterns
Design PatternsDesign Patterns
Design Patternssoms_1
 
Creational pattern
Creational patternCreational pattern
Creational pattern
Himanshu
 
Design patterns english
Design patterns englishDesign patterns english
Design patterns english
meriem sari
 
Object Interconnections
Object InterconnectionsObject Interconnections
Object Interconnections
adil raja
 
Solid js
Solid jsSolid js
Solid js
jonathanfmills
 
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
 
Go f designpatterns 130116024923-phpapp02
Go f designpatterns 130116024923-phpapp02Go f designpatterns 130116024923-phpapp02
Go f designpatterns 130116024923-phpapp02
Jagath Bandara Senanayaka
 

What's hot (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
 

Viewers also liked

Lição prova professor coordenador
Lição prova professor coordenadorLição prova professor coordenador
Lição prova professor coordenador
Paulo Gandra de Sousa
 
REST beyond CRUD
REST beyond CRUDREST beyond CRUD
REST beyond CRUD
Paulo Gandra de Sousa
 
Rest web services
Rest web servicesRest web services
Rest web services
Paulo Gandra de Sousa
 
PoEAA by Example
PoEAA by ExamplePoEAA by Example
PoEAA by Example
Paulo Gandra de Sousa
 
Modern web architectural patterns
Modern web architectural patternsModern web architectural patterns
Modern web architectural patterns
Paulo Gandra de Sousa
 
RESTful services Design Lab
RESTful services Design LabRESTful services Design Lab
RESTful services Design Lab
Paulo Gandra de Sousa
 
Benefits of Hypermedia API
Benefits of Hypermedia APIBenefits of Hypermedia API
Benefits of Hypermedia API
Paulo Gandra de Sousa
 
Software Product Lines
Software Product LinesSoftware Product Lines
Software Product Lines
Paulo 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
 

Viewers also liked (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)
 

Similar to 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 Angular
Jennifer Estrada
 
[iOS] Data Storage
[iOS] Data Storage[iOS] Data Storage
[iOS] Data Storage
Nikmesoft Ltd
 
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
Antonio de la Torre Fernández
 
Orm and hibernate
Orm and hibernateOrm and hibernate
Orm and hibernate
s4al_com
 
Best interview questions
Best interview questionsBest interview questions
Best interview questions
Thesis Scientist Private Limited
 
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
Greg Szczotka
 
Identity Manager Opensource OpenIDM Architecture
Identity Manager Opensource OpenIDM ArchitectureIdentity Manager Opensource OpenIDM Architecture
Identity Manager Opensource OpenIDM Architecture
Aidy Tificate
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptx
anguraju1
 
Software Design principales
Software Design principalesSoftware Design principales
Software Design principales
ABDEL RAHMAN KARIM
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
Mojammel Haque
 
Clean architecture: Android
Clean architecture: AndroidClean architecture: Android
Clean architecture: Androidintive
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
Ahmad Hussein
 
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
 
CS8592-OOAD Lecture Notes Unit-4
CS8592-OOAD Lecture Notes Unit-4CS8592-OOAD Lecture Notes Unit-4
CS8592-OOAD Lecture Notes Unit-4
Gobinath Subramaniam
 
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 Design
Irwansyah 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
 

Similar to 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)
 

More from Paulo Gandra de Sousa

Introduction to Microservices
Introduction to MicroservicesIntroduction to Microservices
Introduction to Microservices
Paulo Gandra de Sousa
 
Minds-on DDD
Minds-on DDDMinds-on DDD
Minds-on DDD
Paulo Gandra de Sousa
 
Introduction to microservices
Introduction to microservicesIntroduction to microservices
Introduction to microservices
Paulo Gandra de Sousa
 
Design Patterns: Back to Basics
Design Patterns: Back to BasicsDesign Patterns: Back to Basics
Design Patterns: Back to Basics
Paulo Gandra de Sousa
 
Hypermedia APIs
Hypermedia APIsHypermedia APIs
Hypermedia APIs
Paulo Gandra de Sousa
 
Documenting Software Architectures
Documenting Software ArchitecturesDocumenting Software Architectures
Documenting Software Architectures
Paulo Gandra de Sousa
 
Distributed Systems
Distributed SystemsDistributed Systems
Distributed Systems
Paulo Gandra de Sousa
 

More from 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
 

Recently uploaded

Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptxText-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
ShamsuddeenMuhammadA
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Crescat
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
Aftab Hussain
 
Top 7 Unique WhatsApp API Benefits | Saudi Arabia
Top 7 Unique WhatsApp API Benefits | Saudi ArabiaTop 7 Unique WhatsApp API Benefits | Saudi Arabia
Top 7 Unique WhatsApp API Benefits | Saudi Arabia
Yara Milbes
 
Pro Unity Game Development with C-sharp Book
Pro Unity Game Development with C-sharp BookPro Unity Game Development with C-sharp Book
Pro Unity Game Development with C-sharp Book
abdulrafaychaudhry
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
Aftab Hussain
 

Recently uploaded (20)

Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptxText-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
 
Top 7 Unique WhatsApp API Benefits | Saudi Arabia
Top 7 Unique WhatsApp API Benefits | Saudi ArabiaTop 7 Unique WhatsApp API Benefits | Saudi Arabia
Top 7 Unique WhatsApp API Benefits | Saudi Arabia
 
Pro Unity Game Development with C-sharp Book
Pro Unity Game Development with C-sharp BookPro Unity Game Development with C-sharp Book
Pro Unity Game Development with C-sharp Book
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
 

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