SlideShare a Scribd company logo
1 of 52
Download to read offline
Beyond Design Principles & Patterns
Writing good OO code
Matthias Noback
@matthiasnoback
Design patterns
● Abstract factory
● Mediator
● Proxy
● Builder
● Composite
● Chain of responsibility
● Adapter
● Strategy
● Façade
● Bridge
● Observer
● Singleton
● Factory method
● Command
Design principles, and more patterns
● Class principles (SOLID)
● Package design principles
● Tactical DDD patterns
● Testing patterns
● Architectural patterns
Education
● Refer to books (but nobody reads them)
● In interviews: “Do you know SOLID?”
● Knowing is one thing, applying it is something
else.
Back to basics
Any class can serve as the blueprint of an object,
but not every object will be a Good Objecttm
Objects introduce meaning
By wrapping primitive values
Class name = Type
Strings
Email
addresses
Floats
Latitude
If not every string counts as an email address,
introduce a dedicated type: EmailAddress.
If not every integer counts as an age, introduce a
dedicated type: Age.
And so on!
Objects keep together what belongs
together
Latitude and Longitude
X and Y
Amount and Currency
Distance and Unit
...
Cohesion
What is together belongs together.
Cohesion
What belongs together, gets together.
Objects attract related data and behavior.
Objects bring together meaningful
behaviors
Coordinates.distanceTo(Coordinates other): Distance
Money.convertTo(Currency other): Money
Map.set(String key, T item): void
Map.get(String key): T
Array.push(T item): void
Array.pop(): T
Objects
State & Behavior
final class Coordinates
{
private Latitude latitude;
private Longitude longitude;
public function halfwayTo(
Coordinates other
): Coordinates {
// ...
}
}
State
Behavior
Primitive
values Entities
Value
objects
Services
Anemic
domain
objects
For all objects
Make sure they can't exist in an incoherent or
inconsistent state
At construction time
● Provide the right data (values, value objects)
● Provide the right services (collaborating objects)
// no setter injection
service = new Service();
service.setLogger(...);
// no setter party
object = new Object();
object.setFoo(...);
object.setBar(...);
At modification time
● Provide the right data (values, value objects)
What's the “right” data?
● Valid (correct types, correct number of things,
etc.)
● Meaningful (within an allowed range, pattern,
etc.)
What's the “right” data?
Only allow transitions that make sense
final class Order
{
public function cancel(...): void
{
if (wasShipped) {
throw new LogicException(...);
}
}
}
When implementing behavior: follow
this recipe
public function someMethod(int $value)
{
// check pre-conditions
Assertion::greaterThan($value, 0);
// fail early
if (...) {
throw new RuntimeException(...);
}
// happy path: at "0" indent
// check post-conditions
return ...;
}
Command/Query Separation
Every method is either
a command or a query method.
public function commandMethod(...): void
{
/*
* Changes observable state of the system
*
* May have side effects:
* - network calls
* - filesystem changes
*
* Returns nothing.
* May throw an exception.
*/
}
public function queryMethod(...): [specific type]
{
/*
* Returns something, doesn't change
* anything.
*
* May throw an exception.
*/
}
CQS principle
Asking for information doesn’t
change observable state.
Return single-type values
● Object of specific type, or an exception
● List with values of specific type, or an empty list
public function queryMethod(...): [specific type]
{
if (...) {
throw new RuntimeException(...);
}
return objectOfSpecificType;
}
public function queryMethod(...): List
{
if (...) {
return List::empty();
}
return List::of(...);
}
At failure time
Throw useful and detailed exceptions
Defensive programming
Recover from failure?
No, usually: scream about it!
Offensive programming
Add lots of sanity checks and throw exceptions.
Assert::greaterThan(...);
Assert::count(...);
...
State versus behavior, revisited
Objects have state and behavior
But they hide data and implementation details
State versus behavior, revisited
Expose more behavior, less state
Treat your objects as black boxes
When writing tests for them
Don't test constructors by calling
getters
Give the object a good reason to remember
something, and describe that reason in a test.
public function it_can_be_constructed(): void
{
money = new Money(1000, new Currency('EUR'));
assertEquals(
1000,
money.getAmount()
);
assertEquals(
'EUR',
money.getCurrency().asString()
);
}
Getters just
for testing!
public function it_can_be_converted(): void
{
money = new Money(1000, new Currency('EUR'));
rate = new ExchangeRate(
new Currency('EUR'),
new Currency('USD'),
1.23456
);
converted = money.convert(rate);
assertEquals(
new Money(
1235, // rounded to the second digit
new Currency('USD')
)
converted
);
}
No getters!
Nor testing them!
Guiding experiment
Only add a getter if
something other than a test needs it.
Changing the behavior of an object
Always aim to do it without touching the code of its class
(let it remain a black box!)
class Game
{
public function move(): void
{
steps = this.roll();
}
private function roll(): int
{
return randomInt(1, 6);
}
}
How to use a
hard-coded value
for testing?
class Game
{
public function move(): void
{
steps = this.roll();
}
protected function roll(): int
{
return randomInt(1, 6);
}
}
class GameWithFixedRoll extends Game
{
protected function roll(): int
{
return 6;
}
}
final class Game
{
private Die die;
public function __construct(Die die)
{
this.die = die;
}
public function move(): void
{
steps = this.die.roll();
}
}
interface Die
{
public function roll(): int;
}
Dependency injection!
Composition instead of
inheritance
Final classes!
final RandomDie implements Die
{
public function roll(): int
{
return randomInt(1, 6);
}
}
final FixedDie implements Die
{
public function __construct(value)
{
this.value = value;
}
public function roll(): int
{
return this.value;
}
}
Technically a test double
called “stub”
Behavior can be modified
without touching the code
“Composition over inheritance”
Changing the behavior of objects by composing
them in different ways
(as opposed to using inheritance to override
behavior)
Create better objects
● Introduce more types.
● Be more strict about them.
● Design objects that only accept valid data.
● Design objects that can only be used in valid
ways.
● Use composition instead of inheritance to
change an object's behavior.
Well designed objects lead to an application that
almost clicks together
Questions?
Matthias Noback
@matthiasnoback

More Related Content

What's hot

C# Starter L03-Utilities
C# Starter L03-UtilitiesC# Starter L03-Utilities
C# Starter L03-Utilities
Mohammad Shaker
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
singhadarsh
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharp
g_hemanth17
 
Introduction to CSharp
Introduction to CSharpIntroduction to CSharp
Introduction to CSharp
Mody Farouk
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
Raga Vahini
 
Functions and Objects in JavaScript
Functions and Objects in JavaScript Functions and Objects in JavaScript
Functions and Objects in JavaScript
Dhananjay Kumar
 

What's hot (17)

INHERITANCE IN C++ +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
INHERITANCE IN C++ +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUSINHERITANCE IN C++ +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
INHERITANCE IN C++ +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
 
C# Starter L03-Utilities
C# Starter L03-UtilitiesC# Starter L03-Utilities
C# Starter L03-Utilities
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharp
 
Introduction to CSharp
Introduction to CSharpIntroduction to CSharp
Introduction to CSharp
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Session 08 - OOP with Java - continued
Session 08 - OOP with Java - continuedSession 08 - OOP with Java - continued
Session 08 - OOP with Java - continued
 
Android Development Course in HSE lecture #2
Android Development Course in HSE lecture #2Android Development Course in HSE lecture #2
Android Development Course in HSE lecture #2
 
Developing Applications for Android - Lecture#2
Developing Applications for Android - Lecture#2Developing Applications for Android - Lecture#2
Developing Applications for Android - Lecture#2
 
Class object method constructors in java
Class object method constructors in javaClass object method constructors in java
Class object method constructors in java
 
4.trasformers filters-adapters
4.trasformers filters-adapters4.trasformers filters-adapters
4.trasformers filters-adapters
 
Session 09 - OOPS
Session 09 - OOPSSession 09 - OOPS
Session 09 - OOPS
 
Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)
 
JavaScript Data Types
JavaScript Data TypesJavaScript Data Types
JavaScript Data Types
 
Functions and Objects in JavaScript
Functions and Objects in JavaScript Functions and Objects in JavaScript
Functions and Objects in JavaScript
 
Pythia Reloaded: An Intelligent Unit Testing-Based Code Grader for Education
Pythia Reloaded: An Intelligent Unit Testing-Based Code Grader for EducationPythia Reloaded: An Intelligent Unit Testing-Based Code Grader for Education
Pythia Reloaded: An Intelligent Unit Testing-Based Code Grader for Education
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 

Similar to Beyond design principles and patterns (muCon 2019 edition)

33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
Tomek Kaczanowski
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.js
Jarod Ferguson
 
Intro to object oriented programming
Intro to object oriented programmingIntro to object oriented programming
Intro to object oriented programming
David Giard
 

Similar to Beyond design principles and patterns (muCon 2019 edition) (20)

Beyond Design Principles and Patterns
Beyond Design Principles and PatternsBeyond Design Principles and Patterns
Beyond Design Principles and Patterns
 
DPC 2019, Amsterdam: Beyond design patterns and principles - writing good OO ...
DPC 2019, Amsterdam: Beyond design patterns and principles - writing good OO ...DPC 2019, Amsterdam: Beyond design patterns and principles - writing good OO ...
DPC 2019, Amsterdam: Beyond design patterns and principles - writing good OO ...
 
#pugMi - DDD - Value objects
#pugMi - DDD - Value objects#pugMi - DDD - Value objects
#pugMi - DDD - Value objects
 
TDD and mobile development: some forgotten techniques, illustrated with Android
TDD and mobile development: some forgotten techniques, illustrated with AndroidTDD and mobile development: some forgotten techniques, illustrated with Android
TDD and mobile development: some forgotten techniques, illustrated with Android
 
Clean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 Function
 
Maintainable JavaScript 2011
Maintainable JavaScript 2011Maintainable JavaScript 2011
Maintainable JavaScript 2011
 
Unit testing with PHPUnit - there's life outside of TDD
Unit testing with PHPUnit - there's life outside of TDDUnit testing with PHPUnit - there's life outside of TDD
Unit testing with PHPUnit - there's life outside of TDD
 
Writing testable code
Writing testable codeWriting testable code
Writing testable code
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
Iterative architecture
Iterative architectureIterative architecture
Iterative architecture
 
Andriy Slobodyanyk "How to Use Hibernate: Key Problems and Solutions"
Andriy Slobodyanyk "How to Use Hibernate: Key Problems and Solutions"Andriy Slobodyanyk "How to Use Hibernate: Key Problems and Solutions"
Andriy Slobodyanyk "How to Use Hibernate: Key Problems and Solutions"
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.js
 
Programming picaresque
Programming picaresqueProgramming picaresque
Programming picaresque
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features Summary
 
Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code Smells
 
Intro to object oriented programming
Intro to object oriented programmingIntro to object oriented programming
Intro to object oriented programming
 
Cleaner Code - CodeStock 2019 Edition
Cleaner Code - CodeStock 2019 EditionCleaner Code - CodeStock 2019 Edition
Cleaner Code - CodeStock 2019 Edition
 
Scala for Java Developers
Scala for Java DevelopersScala for Java Developers
Scala for Java Developers
 
Internet programming slide - java.ppt
Internet programming slide - java.pptInternet programming slide - java.ppt
Internet programming slide - java.ppt
 

More from Matthias Noback

Advanced web application architecture - PHP Barcelona
Advanced web application architecture  - PHP BarcelonaAdvanced web application architecture  - PHP Barcelona
Advanced web application architecture - PHP Barcelona
Matthias Noback
 
A testing strategy for hexagonal applications
A testing strategy for hexagonal applicationsA testing strategy for hexagonal applications
A testing strategy for hexagonal applications
Matthias Noback
 

More from Matthias Noback (20)

Rector fireside chat - PHPMiNDS meetup
Rector fireside chat - PHPMiNDS meetupRector fireside chat - PHPMiNDS meetup
Rector fireside chat - PHPMiNDS meetup
 
Service abstractions - Part 1: Queries
Service abstractions - Part 1: QueriesService abstractions - Part 1: Queries
Service abstractions - Part 1: Queries
 
Hexagonal Symfony - SymfonyCon Amsterdam 2019
Hexagonal Symfony - SymfonyCon Amsterdam 2019Hexagonal Symfony - SymfonyCon Amsterdam 2019
Hexagonal Symfony - SymfonyCon Amsterdam 2019
 
Advanced web application architecture - PHP Barcelona
Advanced web application architecture  - PHP BarcelonaAdvanced web application architecture  - PHP Barcelona
Advanced web application architecture - PHP Barcelona
 
A testing strategy for hexagonal applications
A testing strategy for hexagonal applicationsA testing strategy for hexagonal applications
A testing strategy for hexagonal applications
 
Advanced web application architecture - Talk
Advanced web application architecture - TalkAdvanced web application architecture - Talk
Advanced web application architecture - Talk
 
Layers, ports and adapters
Layers, ports and adaptersLayers, ports and adapters
Layers, ports and adapters
 
Brutal refactoring, lying code, the Churn, and other emotional stories from L...
Brutal refactoring, lying code, the Churn, and other emotional stories from L...Brutal refactoring, lying code, the Churn, and other emotional stories from L...
Brutal refactoring, lying code, the Churn, and other emotional stories from L...
 
Advanced web application architecture Way2Web
Advanced web application architecture Way2WebAdvanced web application architecture Way2Web
Advanced web application architecture Way2Web
 
Brutal refactoring, lying code, the Churn, and other emotional stories from L...
Brutal refactoring, lying code, the Churn, and other emotional stories from L...Brutal refactoring, lying code, the Churn, and other emotional stories from L...
Brutal refactoring, lying code, the Churn, and other emotional stories from L...
 
Building Autonomous Services
Building Autonomous ServicesBuilding Autonomous Services
Building Autonomous Services
 
Advanced Application Architecture Symfony Live Berlin 2018
Advanced Application Architecture Symfony Live Berlin 2018Advanced Application Architecture Symfony Live Berlin 2018
Advanced Application Architecture Symfony Live Berlin 2018
 
Designing for Autonomy
Designing for AutonomyDesigning for Autonomy
Designing for Autonomy
 
Docker workshop
Docker workshopDocker workshop
Docker workshop
 
Docker swarm workshop
Docker swarm workshopDocker swarm workshop
Docker swarm workshop
 
Docker compose workshop
Docker compose workshopDocker compose workshop
Docker compose workshop
 
Building autonomous services
Building autonomous servicesBuilding autonomous services
Building autonomous services
 
Designing for autonomy
Designing for autonomyDesigning for autonomy
Designing for autonomy
 
Advanced application architecture
Advanced application architectureAdvanced application architecture
Advanced application architecture
 
Continously delivering containerized microservices
Continously delivering containerized microservicesContinously delivering containerized microservices
Continously delivering containerized microservices
 

Recently uploaded

Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
masabamasaba
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 

Recently uploaded (20)

%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 

Beyond design principles and patterns (muCon 2019 edition)