SlideShare a Scribd company logo
Reviewing OOP design patterns
Olivier Bacs
@reallyoli
Introduction
Definition
In software engineering, a software design pattern is a general reusable
solution to a commonly occurring problem within a given context in
software design.
It is not a finished design that can be transformed directly into source
code.
The implementation approaches tend to be slightly different.
Why spend the time?
- From framework user, to framework creator in a software engineer
career
- Where to direct our attention: brush up on foundations, not
frameworks
- … And time is finite. Why spend too much time on a problem that has
been solved already?
History
1977: Christopher Alexander introduces the idea of patterns: successful
solutions to problems. (Pattern Language)
1987: Ward Cunningham and Kent Beck leverage Alexander’s idea in the
context of an OO language.
1987: Eric Gamma’s dissertation on importance of patterns and how to
capture them.
1994: The book =>
The core tenets
of OOP
Core principles of OOP:
Encapsulation
const account = { balance: 1000, owner: 13466 }
example: a bank account object
Core principles of OOP:
Encapsulation
const account = { balance: 1000, owner: 13466 }
-> Encapsulate the properties
! Manipulating properties directly
example: a bank account object
Core principles of OOP:
Encapsulation
class Account {
private balance: number
private owner: Customer
public withdraw(amount: number) { // can validate }
public deposit(amount: number) {}
}
Its public API
const account = { balance: 1000, owner: 13466 }
The object’s internals, what you hide / protect
connectToRemoteServer(){}
validateTokenLength(){}
disconnectFromRemoteServer(){}
moreAndMoreSteps(){}
Core principles of OOP:
Abstractions
example: an email distribution API SDK
connectToRemoteServer(){}
validateTokenLength(){}
disconnectFromRemoteServer(){}
moreAndMoreSteps(){}
Core principles of OOP:
Abstractions
-> Abstract those activities
! Remove lower level concerns
! Protect from breaking changes in API
example: an email distribution API SDK
class EmailService {
private connectToRemoteServer(){}
private validateTokenLength(){}
private disconnectFromRemoteServer(){}
public sendEmail(){ // leverages all the above }
}
Core principles of OOP:
Abstractions
Things that might be extended/removed
be quite complex...
A neat public API
Core principles of OOP:
Inheritance
class Rectangle {
fillShape(){ // }
}
example: an design app
class Circle {
fillShape(){ // }
}
Core principles of OOP:
Inheritance
class Rectangle {
fillShape(){ // }
}
example: an design app
class Circle {
fillShape(){ // }
}
! Make your code more DRY by avoiding repetitions
-> Add logic to a common ancestor
Core principles of OOP:
Inheritance
example: an design app
class Shape {
public fill(colour: string){ //behaviour }
}
class Circle extends Shape {}
const circle = new Circle()
circle.fill(”#FF0000”)
A way to write logic once and update it
downward
Quick recall: the concept of interfaces
An interface is a reference type in OOP.
A reference Type is a “specification type”. We can’t explicitly use it, but it is used
internally by the language.
It enforces a contract that the derived classes will have to obey
Interfaces are an “ideal”
Core principles of OOP:
Polymorphism( “Can take many forms” )
example: an animal game for children
interface IAnimal {
makeSound(): string
}
abstract class AbstractAnimal {
abstract makeSound(): string
}
the prefix I is a Convention
Core principles of OOP:
Polymorphism( “Can take many forms” )
example: an animal game for children
class Cat implements IAnimal {
public makeSound():string { return “Miaou” }
}
class Cat extend AbstractAnimal {
public makeSound():string { return “Miaou” }
}
Your “API” to other classes
Quick recall: access modifiers
Design principles
of construction
Fundamental principles
Avoiding duplication
A common name, and enough similarities might trump misleading
if(customer !== null && customer.length !== 0) {
// logic
}
if(customer !== null && typeof customer !== “undefined”) {
// logic
}
34
156
Code can drift over time
Fundamental principles
Avoiding tight coupling
A loosely coupled system
Fixing tire !== fixing dashboard or seatbelt
An architectural ideal
Fundamental principles
Single responsibility principle, see your code as modular black boxes
Easier to explain
Less surprising
Class is much less likely to
change often
The name should be able to
tell you what it does
Open-Close principle
Open to extension, closed for modification
class CoffeeMaker {
final grindCoffee(): void
final runJob(program: string): void
}
class FancyCoffeMaker extends CoffeeMaker {
runJob(program: string, callback: Function): void
}
Inheritance bring tight coupling
New features should not change the
base class
! Open
!! New feature !!
Don’t change
Dependency Injection
High level modules should not depend upon low level modules.
class EmployeSearchService {
private employeesTable = new DBConnection(3306, “somewhere.”, “admin”, “admin123”, “employees”);
public getById(id: string) {
return this.employeesTable.findbyId(id);
}
}
Dependency Injection
High level modules should not depend upon low level modules.
class EmployeSearchService {
private employeesTable = new DBConnection(3306, “somewhere.”, “admin”, “admin123”, “employees”);
public getById(id: string) {
return this.employeesTable.findbyId(id);
}
}
!! New feature !! Extended search
Dependency Injection
High level modules should not depend upon low level modules.
class EmployeSearchService {
private employeeDataStore: EmployeeDataStore
constructor(dataStore: EmployeeDataStore) {
this.employeeDataStore = dataStore
}
public getById(id: string) {
return this.employeeDataStore.findbyId(id);
}
}
new EmployeeSearchService(new EmployeeNapkins())
new EmployeeSearchService(new ExmployeeExcel())
new EmployeeSearchService(new EmployeeCSV())
Give the stores a common interface
Make your code more flexible
Fundamental principles
- LSP: Liskov Substitution Principle.
Derived classes must be substitutable for their base classes
- ISP: Interface Segregation Principle
Client should not be forced to depend upon interfaces they do not use
Design patterns
Recall: UML
A visual, language agnostic way to map OOP: Unified Modelling Language
Access:
+ public - private # protected
Properties
class name
Methods
The Five Families of Design Patterns
Creational
Structural Foundational
Concurrency
Behavioural
Modern days design pattern families
The Three Main Families of Design Patterns
Behavioural
Structural
Creational
According to the Gang of Four
23 design patterns
Behavioural Patterns
Used to responsibilities between objects and manage algorithms
● Command
● Observer
● Strategy
● State
● Visitor
● Memento
● Mediator
● Iterator
Structural Patterns
Used to form large structures between many disparate objects
● Adapter
● Proxy
● Decorator
● Facade
● Aggregate
● Bridge
Creational Patterns
Used to construct object so that they can be decoupled from their
implementing system
● Singleton
● Factory Method Pattern
● Abstract Factory
● Builder
● Prototype
Behavioural Patterns
Command pattern: An object oriented replacement for callbacks
“Encapsulate a request as an object, thereby letting users parameterize
clients with different requests, queue or log request, and support
undoable operations”
Behavioural Patterns
Command pattern: An object oriented replacement for callbacks
example: configuring input on a game controller
Y
X B
A
Fire Gun
Jump
Duck
Swap weapon
You want to:
> Map inputs to actions in an OO way
Behavioural Patterns
Command pattern: An object oriented replacement for callbacks
example: game controller commands
class InputHandler {
static handleInput() {
if(isPressed(BUTTON_X) jump()
else if(isPressed(BUTTON_Y) fireGun()
else if(isPressed(BUTTON_A) swapWeapon()
else if(isPressed(BUTTON_B) duck()
}
}
Behavioural Patterns
Command pattern: An object oriented replacement for callbacks
example: game controller commands
Users usually like to map
their own controls to the
inputs
class InputHandler {
static handleInput() {
if(isPressed(BUTTON_X) jump()
else if(isPressed(BUTTON_Y) fireGun()
else if(isPressed(BUTTON_A) swapWeapon()
else if(isPressed(BUTTON_B) duck()
}
}
Behavioural Patterns
Command pattern: An object oriented replacement for callbacks
example: game controller commands
> You want to make the direct calls to jump() and fireGun() into something that we can swap
in and out.
Behavioural Patterns
Command pattern: An object oriented replacement for callbacks
example: game controller commands
interface ICommand {
execute():void
}
class JumpCommand implements ICommand{
execute(): void { jump(); }
}
class DuckCommand implements ICommand{
execute():void { duck(); }
}
class InputHandler {
private buttonA: Command;
private buttonB: Command;
private buttonX: Command;
private buttonY: Command;
public setButtonA(command: Command): void {this.buttonA = command;}
public setButtonB(command: Command): void {this.buttonB = command;}
public setButtonX(command: Command): void {this.buttonX = command;}
public setButtonY(command: Command): void {this.buttonY = command;}
}
Behavioural Patterns
Command pattern: An object oriented replacement for callbacks
class InputHandler {
...
public inputHandler():void {
if(isPressed(BUTTON_X) return buttonX.execute()
else if(isPressed(BUTTON_Y) return buttonY.execute()
else if(isPressed(BUTTON_A) return buttonA.execute()
else if(isPressed(BUTTON_B) return buttonB.execute()
return null
}
}
Behavioural Patterns
Command pattern: An object oriented replacement for callbacks
Behavioural Patterns
Command pattern: An object oriented replacement for callbacks
Y
X B
A
Fire Gun
Jump
Duck
Swap weapon
Behavioural Patterns
Command pattern: An object oriented replacement for callbacks
Bonus: Undoing things
interface ICommand {
execute():void
undo():void
}
Behavioural Patterns
Command pattern: An object oriented replacement for callbacks
class MoveUnit {
private x: number;
private y: number;
private xBefore: number;
private yBefore: number;
private unit: ArmyUnit;
constructor(unit: ArmyUnit, x: number, y: number){
this.x = x;
this.y = y;
}
public execute(){
this.xBefore = this.x;
this.yBefore = this.y;
this.unit.moveTo(this.x, this.y)
}
public undo(){
this.unit.moveTo(this.xBefore, this.yBefore)
}
}
CMD CMD CMD CMD CMD
Older Newer
An undo stack
example: a turn by turn strategy game
Undo Redo
Creational Patterns
Singleton pattern: There is power in ONE
“The singleton pattern ensures that only one object of a particular class
is ever created. All further references to objects of the singleton class
refer to the same underlying instance.’
Creational Patterns
Singleton pattern: There is power in ONE
example: a logger
> You want to create a logger that adds log lines to files from different locations and
potentially at the same time
> You logs have to maintain the order of the events
> You need to avoid “file already in use” and other lock related issues
Creational Patterns
Singleton pattern: There is power in ONE
example: a logger
Not just for a logger, but for most of the xManager, xEngine, xSystem classes of
objects.
Like
- DBConnectionManager
- FilesystemManager
- ...
Creational Patterns
Singleton pattern: There is power in ONE
A solution is provided by the singleton pattern:
Enforcing a single global instance that wraps resources you want to protect
Creational Patterns
Singleton pattern: There is power in ONE
example: a logger
class Logger {
private static _instance: MyClass;
private constructor() { // initialisation... }
public static getInstance() {
return this._instance || (this._instance = new this());
}
}
const logger = Logger.getInstance();
Creational Patterns
Singleton pattern: There is power is ONE
Global state
Not garbage
collected
There for the
entire life of
the program
*
*Once lazy loaded
Theoretically
accessible from
everywhere
Resources
Another take: The anti patterns http://www.laputan.org/mud/
Build your UML graphs with Lucid Charts
https://www.lucidchart.com/pages/examples/uml_diagram_tool
Readings
Tools
@reallyoli
Ad

More Related Content

What's hot (20)

Introduction to object oriented programming
Introduction to object oriented programmingIntroduction to object oriented programming
Introduction to object oriented programming
Abzetdin Adamov
 
Concepts In Object Oriented Programming Languages
Concepts In Object Oriented Programming LanguagesConcepts In Object Oriented Programming Languages
Concepts In Object Oriented Programming Languages
ppd1961
 
4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT
Ajay Chimmani
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPT
kishu0005
 
Object-oriented programming
Object-oriented programmingObject-oriented programming
Object-oriented programming
Neelesh Shukla
 
Advance oops concepts
Advance oops conceptsAdvance oops concepts
Advance oops concepts
Sangharsh agarwal
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#
Doncho Minkov
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
Bhushan Nagaraj
 
C++ [ principles of object oriented programming ]
C++ [ principles of object oriented programming ]C++ [ principles of object oriented programming ]
C++ [ principles of object oriented programming ]
Rome468
 
SEMINAR
SEMINARSEMINAR
SEMINAR
priteshkhandelwal
 
Basic concepts of oops
Basic concepts of oopsBasic concepts of oops
Basic concepts of oops
Chandrakiran Satdeve
 
Oop in c++ lecture 1
Oop in c++  lecture 1Oop in c++  lecture 1
Oop in c++ lecture 1
zk75977
 
Introduction to oop
Introduction to oopIntroduction to oop
Introduction to oop
colleges
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
Abhigyan Singh Yadav
 
class and objects
class and objectsclass and objects
class and objects
Payel Guria
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
emailharmeet
 
Introduction to OOP in Python
Introduction to OOP in PythonIntroduction to OOP in Python
Introduction to OOP in Python
Aleksander Fabijan
 
OOPS in Java
OOPS in JavaOOPS in Java
OOPS in Java
Zeeshan Khan
 
SKILLWISE - OOPS CONCEPT
SKILLWISE - OOPS CONCEPTSKILLWISE - OOPS CONCEPT
SKILLWISE - OOPS CONCEPT
Skillwise Group
 
Oops Concept Java
Oops Concept JavaOops Concept Java
Oops Concept Java
Kamlesh Singh
 
Introduction to object oriented programming
Introduction to object oriented programmingIntroduction to object oriented programming
Introduction to object oriented programming
Abzetdin Adamov
 
Concepts In Object Oriented Programming Languages
Concepts In Object Oriented Programming LanguagesConcepts In Object Oriented Programming Languages
Concepts In Object Oriented Programming Languages
ppd1961
 
4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT
Ajay Chimmani
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPT
kishu0005
 
Object-oriented programming
Object-oriented programmingObject-oriented programming
Object-oriented programming
Neelesh Shukla
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#
Doncho Minkov
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
Bhushan Nagaraj
 
C++ [ principles of object oriented programming ]
C++ [ principles of object oriented programming ]C++ [ principles of object oriented programming ]
C++ [ principles of object oriented programming ]
Rome468
 
Oop in c++ lecture 1
Oop in c++  lecture 1Oop in c++  lecture 1
Oop in c++ lecture 1
zk75977
 
Introduction to oop
Introduction to oopIntroduction to oop
Introduction to oop
colleges
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
Abhigyan Singh Yadav
 
class and objects
class and objectsclass and objects
class and objects
Payel Guria
 
SKILLWISE - OOPS CONCEPT
SKILLWISE - OOPS CONCEPTSKILLWISE - OOPS CONCEPT
SKILLWISE - OOPS CONCEPT
Skillwise Group
 

Similar to Reviewing OOP Design patterns (20)

conceptsinobjectorientedprogramminglanguages-12659959597745-phpapp02.pdf
conceptsinobjectorientedprogramminglanguages-12659959597745-phpapp02.pdfconceptsinobjectorientedprogramminglanguages-12659959597745-phpapp02.pdf
conceptsinobjectorientedprogramminglanguages-12659959597745-phpapp02.pdf
SahajShrimal1
 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - Warburton
Codemotion
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
RichardWarburton
 
Dependency Injection: Why is awesome and why should I care?
Dependency Injection: Why is awesome and why should I care?Dependency Injection: Why is awesome and why should I care?
Dependency Injection: Why is awesome and why should I care?
devObjective
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
ColdFusionConference
 
Dependency Injection Why is it awesome and Why should I care?
Dependency Injection Why is it awesome and Why should I care?Dependency Injection Why is it awesome and Why should I care?
Dependency Injection Why is it awesome and Why should I care?
ColdFusionConference
 
Patterns in Python
Patterns in PythonPatterns in Python
Patterns in Python
dn
 
2009 Dotnet Information Day: More effective c#
2009 Dotnet Information Day: More effective c#2009 Dotnet Information Day: More effective c#
2009 Dotnet Information Day: More effective c#
Daniel Fisher
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLs
intelliyole
 
Gdd pydp
Gdd pydpGdd pydp
Gdd pydp
Олег Иванов
 
Framework engineering JCO 2011
Framework engineering JCO 2011Framework engineering JCO 2011
Framework engineering JCO 2011
YoungSu Son
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
Iván Fernández Perea
 
Functions in c
Functions in cFunctions in c
Functions in c
reshmy12
 
The Larch - a visual interactive programming environment
The Larch - a visual interactive programming environmentThe Larch - a visual interactive programming environment
The Larch - a visual interactive programming environment
Python Ireland
 
Design patters java_meetup_slideshare [compatibility mode]
Design patters java_meetup_slideshare [compatibility mode]Design patters java_meetup_slideshare [compatibility mode]
Design patters java_meetup_slideshare [compatibility mode]
Dimitris Dranidis
 
Framework Design Guidelines For Brussels Users Group
Framework Design Guidelines For Brussels Users GroupFramework Design Guidelines For Brussels Users Group
Framework Design Guidelines For Brussels Users Group
brada
 
Dependency injectionpreso
Dependency injectionpresoDependency injectionpreso
Dependency injectionpreso
ColdFusionConference
 
Object Oriented Concepts and Principles
Object Oriented Concepts and PrinciplesObject Oriented Concepts and Principles
Object Oriented Concepts and Principles
deonpmeyer
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design Patterns
Stefano Fago
 
Object-oriented programming (OOP) with Complete understanding modules
Object-oriented programming (OOP) with Complete understanding modulesObject-oriented programming (OOP) with Complete understanding modules
Object-oriented programming (OOP) with Complete understanding modules
Durgesh Singh
 
conceptsinobjectorientedprogramminglanguages-12659959597745-phpapp02.pdf
conceptsinobjectorientedprogramminglanguages-12659959597745-phpapp02.pdfconceptsinobjectorientedprogramminglanguages-12659959597745-phpapp02.pdf
conceptsinobjectorientedprogramminglanguages-12659959597745-phpapp02.pdf
SahajShrimal1
 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - Warburton
Codemotion
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
RichardWarburton
 
Dependency Injection: Why is awesome and why should I care?
Dependency Injection: Why is awesome and why should I care?Dependency Injection: Why is awesome and why should I care?
Dependency Injection: Why is awesome and why should I care?
devObjective
 
Dependency Injection Why is it awesome and Why should I care?
Dependency Injection Why is it awesome and Why should I care?Dependency Injection Why is it awesome and Why should I care?
Dependency Injection Why is it awesome and Why should I care?
ColdFusionConference
 
Patterns in Python
Patterns in PythonPatterns in Python
Patterns in Python
dn
 
2009 Dotnet Information Day: More effective c#
2009 Dotnet Information Day: More effective c#2009 Dotnet Information Day: More effective c#
2009 Dotnet Information Day: More effective c#
Daniel Fisher
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLs
intelliyole
 
Framework engineering JCO 2011
Framework engineering JCO 2011Framework engineering JCO 2011
Framework engineering JCO 2011
YoungSu Son
 
Functions in c
Functions in cFunctions in c
Functions in c
reshmy12
 
The Larch - a visual interactive programming environment
The Larch - a visual interactive programming environmentThe Larch - a visual interactive programming environment
The Larch - a visual interactive programming environment
Python Ireland
 
Design patters java_meetup_slideshare [compatibility mode]
Design patters java_meetup_slideshare [compatibility mode]Design patters java_meetup_slideshare [compatibility mode]
Design patters java_meetup_slideshare [compatibility mode]
Dimitris Dranidis
 
Framework Design Guidelines For Brussels Users Group
Framework Design Guidelines For Brussels Users GroupFramework Design Guidelines For Brussels Users Group
Framework Design Guidelines For Brussels Users Group
brada
 
Object Oriented Concepts and Principles
Object Oriented Concepts and PrinciplesObject Oriented Concepts and Principles
Object Oriented Concepts and Principles
deonpmeyer
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design Patterns
Stefano Fago
 
Object-oriented programming (OOP) with Complete understanding modules
Object-oriented programming (OOP) with Complete understanding modulesObject-oriented programming (OOP) with Complete understanding modules
Object-oriented programming (OOP) with Complete understanding modules
Durgesh Singh
 
Ad

Recently uploaded (20)

ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ijscai
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G..."Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
Infopitaara
 
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Journal of Soft Computing in Civil Engineering
 
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Journal of Soft Computing in Civil Engineering
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
Oil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdfOil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdf
M7md3li2
 
Avnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights FlyerAvnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights Flyer
WillDavies22
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
theory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptxtheory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptx
sanchezvanessa7896
 
Introduction to FLUID MECHANICS & KINEMATICS
Introduction to FLUID MECHANICS &  KINEMATICSIntroduction to FLUID MECHANICS &  KINEMATICS
Introduction to FLUID MECHANICS & KINEMATICS
narayanaswamygdas
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)
Vəhid Gəruslu
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ijscai
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G..."Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
Infopitaara
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
Oil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdfOil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdf
M7md3li2
 
Avnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights FlyerAvnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights Flyer
WillDavies22
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
theory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptxtheory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptx
sanchezvanessa7896
 
Introduction to FLUID MECHANICS & KINEMATICS
Introduction to FLUID MECHANICS &  KINEMATICSIntroduction to FLUID MECHANICS &  KINEMATICS
Introduction to FLUID MECHANICS & KINEMATICS
narayanaswamygdas
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)
Vəhid Gəruslu
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
Ad

Reviewing OOP Design patterns

  • 1. Reviewing OOP design patterns Olivier Bacs @reallyoli
  • 2. Introduction Definition In software engineering, a software design pattern is a general reusable solution to a commonly occurring problem within a given context in software design. It is not a finished design that can be transformed directly into source code. The implementation approaches tend to be slightly different.
  • 3. Why spend the time? - From framework user, to framework creator in a software engineer career - Where to direct our attention: brush up on foundations, not frameworks - … And time is finite. Why spend too much time on a problem that has been solved already?
  • 4. History 1977: Christopher Alexander introduces the idea of patterns: successful solutions to problems. (Pattern Language) 1987: Ward Cunningham and Kent Beck leverage Alexander’s idea in the context of an OO language. 1987: Eric Gamma’s dissertation on importance of patterns and how to capture them. 1994: The book =>
  • 6. Core principles of OOP: Encapsulation const account = { balance: 1000, owner: 13466 } example: a bank account object
  • 7. Core principles of OOP: Encapsulation const account = { balance: 1000, owner: 13466 } -> Encapsulate the properties ! Manipulating properties directly example: a bank account object
  • 8. Core principles of OOP: Encapsulation class Account { private balance: number private owner: Customer public withdraw(amount: number) { // can validate } public deposit(amount: number) {} } Its public API const account = { balance: 1000, owner: 13466 } The object’s internals, what you hide / protect
  • 10. connectToRemoteServer(){} validateTokenLength(){} disconnectFromRemoteServer(){} moreAndMoreSteps(){} Core principles of OOP: Abstractions -> Abstract those activities ! Remove lower level concerns ! Protect from breaking changes in API example: an email distribution API SDK
  • 11. class EmailService { private connectToRemoteServer(){} private validateTokenLength(){} private disconnectFromRemoteServer(){} public sendEmail(){ // leverages all the above } } Core principles of OOP: Abstractions Things that might be extended/removed be quite complex... A neat public API
  • 12. Core principles of OOP: Inheritance class Rectangle { fillShape(){ // } } example: an design app class Circle { fillShape(){ // } }
  • 13. Core principles of OOP: Inheritance class Rectangle { fillShape(){ // } } example: an design app class Circle { fillShape(){ // } } ! Make your code more DRY by avoiding repetitions -> Add logic to a common ancestor
  • 14. Core principles of OOP: Inheritance example: an design app class Shape { public fill(colour: string){ //behaviour } } class Circle extends Shape {} const circle = new Circle() circle.fill(”#FF0000”) A way to write logic once and update it downward
  • 15. Quick recall: the concept of interfaces An interface is a reference type in OOP. A reference Type is a “specification type”. We can’t explicitly use it, but it is used internally by the language. It enforces a contract that the derived classes will have to obey Interfaces are an “ideal”
  • 16. Core principles of OOP: Polymorphism( “Can take many forms” ) example: an animal game for children interface IAnimal { makeSound(): string } abstract class AbstractAnimal { abstract makeSound(): string } the prefix I is a Convention
  • 17. Core principles of OOP: Polymorphism( “Can take many forms” ) example: an animal game for children class Cat implements IAnimal { public makeSound():string { return “Miaou” } } class Cat extend AbstractAnimal { public makeSound():string { return “Miaou” } }
  • 18. Your “API” to other classes Quick recall: access modifiers
  • 20. Fundamental principles Avoiding duplication A common name, and enough similarities might trump misleading if(customer !== null && customer.length !== 0) { // logic } if(customer !== null && typeof customer !== “undefined”) { // logic } 34 156 Code can drift over time
  • 21. Fundamental principles Avoiding tight coupling A loosely coupled system Fixing tire !== fixing dashboard or seatbelt An architectural ideal
  • 22. Fundamental principles Single responsibility principle, see your code as modular black boxes Easier to explain Less surprising Class is much less likely to change often The name should be able to tell you what it does
  • 23. Open-Close principle Open to extension, closed for modification class CoffeeMaker { final grindCoffee(): void final runJob(program: string): void } class FancyCoffeMaker extends CoffeeMaker { runJob(program: string, callback: Function): void } Inheritance bring tight coupling New features should not change the base class ! Open !! New feature !! Don’t change
  • 24. Dependency Injection High level modules should not depend upon low level modules. class EmployeSearchService { private employeesTable = new DBConnection(3306, “somewhere.”, “admin”, “admin123”, “employees”); public getById(id: string) { return this.employeesTable.findbyId(id); } }
  • 25. Dependency Injection High level modules should not depend upon low level modules. class EmployeSearchService { private employeesTable = new DBConnection(3306, “somewhere.”, “admin”, “admin123”, “employees”); public getById(id: string) { return this.employeesTable.findbyId(id); } } !! New feature !! Extended search
  • 26. Dependency Injection High level modules should not depend upon low level modules. class EmployeSearchService { private employeeDataStore: EmployeeDataStore constructor(dataStore: EmployeeDataStore) { this.employeeDataStore = dataStore } public getById(id: string) { return this.employeeDataStore.findbyId(id); } } new EmployeeSearchService(new EmployeeNapkins()) new EmployeeSearchService(new ExmployeeExcel()) new EmployeeSearchService(new EmployeeCSV()) Give the stores a common interface Make your code more flexible
  • 27. Fundamental principles - LSP: Liskov Substitution Principle. Derived classes must be substitutable for their base classes - ISP: Interface Segregation Principle Client should not be forced to depend upon interfaces they do not use
  • 29. Recall: UML A visual, language agnostic way to map OOP: Unified Modelling Language Access: + public - private # protected Properties class name Methods
  • 30. The Five Families of Design Patterns Creational Structural Foundational Concurrency Behavioural Modern days design pattern families
  • 31. The Three Main Families of Design Patterns Behavioural Structural Creational According to the Gang of Four 23 design patterns
  • 32. Behavioural Patterns Used to responsibilities between objects and manage algorithms ● Command ● Observer ● Strategy ● State ● Visitor ● Memento ● Mediator ● Iterator
  • 33. Structural Patterns Used to form large structures between many disparate objects ● Adapter ● Proxy ● Decorator ● Facade ● Aggregate ● Bridge
  • 34. Creational Patterns Used to construct object so that they can be decoupled from their implementing system ● Singleton ● Factory Method Pattern ● Abstract Factory ● Builder ● Prototype
  • 35. Behavioural Patterns Command pattern: An object oriented replacement for callbacks “Encapsulate a request as an object, thereby letting users parameterize clients with different requests, queue or log request, and support undoable operations”
  • 36. Behavioural Patterns Command pattern: An object oriented replacement for callbacks example: configuring input on a game controller Y X B A Fire Gun Jump Duck Swap weapon You want to: > Map inputs to actions in an OO way
  • 37. Behavioural Patterns Command pattern: An object oriented replacement for callbacks example: game controller commands class InputHandler { static handleInput() { if(isPressed(BUTTON_X) jump() else if(isPressed(BUTTON_Y) fireGun() else if(isPressed(BUTTON_A) swapWeapon() else if(isPressed(BUTTON_B) duck() } }
  • 38. Behavioural Patterns Command pattern: An object oriented replacement for callbacks example: game controller commands Users usually like to map their own controls to the inputs class InputHandler { static handleInput() { if(isPressed(BUTTON_X) jump() else if(isPressed(BUTTON_Y) fireGun() else if(isPressed(BUTTON_A) swapWeapon() else if(isPressed(BUTTON_B) duck() } }
  • 39. Behavioural Patterns Command pattern: An object oriented replacement for callbacks example: game controller commands > You want to make the direct calls to jump() and fireGun() into something that we can swap in and out.
  • 40. Behavioural Patterns Command pattern: An object oriented replacement for callbacks example: game controller commands interface ICommand { execute():void } class JumpCommand implements ICommand{ execute(): void { jump(); } } class DuckCommand implements ICommand{ execute():void { duck(); } }
  • 41. class InputHandler { private buttonA: Command; private buttonB: Command; private buttonX: Command; private buttonY: Command; public setButtonA(command: Command): void {this.buttonA = command;} public setButtonB(command: Command): void {this.buttonB = command;} public setButtonX(command: Command): void {this.buttonX = command;} public setButtonY(command: Command): void {this.buttonY = command;} } Behavioural Patterns Command pattern: An object oriented replacement for callbacks
  • 42. class InputHandler { ... public inputHandler():void { if(isPressed(BUTTON_X) return buttonX.execute() else if(isPressed(BUTTON_Y) return buttonY.execute() else if(isPressed(BUTTON_A) return buttonA.execute() else if(isPressed(BUTTON_B) return buttonB.execute() return null } } Behavioural Patterns Command pattern: An object oriented replacement for callbacks
  • 43. Behavioural Patterns Command pattern: An object oriented replacement for callbacks Y X B A Fire Gun Jump Duck Swap weapon
  • 44. Behavioural Patterns Command pattern: An object oriented replacement for callbacks Bonus: Undoing things interface ICommand { execute():void undo():void }
  • 45. Behavioural Patterns Command pattern: An object oriented replacement for callbacks class MoveUnit { private x: number; private y: number; private xBefore: number; private yBefore: number; private unit: ArmyUnit; constructor(unit: ArmyUnit, x: number, y: number){ this.x = x; this.y = y; } public execute(){ this.xBefore = this.x; this.yBefore = this.y; this.unit.moveTo(this.x, this.y) } public undo(){ this.unit.moveTo(this.xBefore, this.yBefore) } } CMD CMD CMD CMD CMD Older Newer An undo stack example: a turn by turn strategy game Undo Redo
  • 46. Creational Patterns Singleton pattern: There is power in ONE “The singleton pattern ensures that only one object of a particular class is ever created. All further references to objects of the singleton class refer to the same underlying instance.’
  • 47. Creational Patterns Singleton pattern: There is power in ONE example: a logger > You want to create a logger that adds log lines to files from different locations and potentially at the same time > You logs have to maintain the order of the events > You need to avoid “file already in use” and other lock related issues
  • 48. Creational Patterns Singleton pattern: There is power in ONE example: a logger Not just for a logger, but for most of the xManager, xEngine, xSystem classes of objects. Like - DBConnectionManager - FilesystemManager - ...
  • 49. Creational Patterns Singleton pattern: There is power in ONE A solution is provided by the singleton pattern: Enforcing a single global instance that wraps resources you want to protect
  • 50. Creational Patterns Singleton pattern: There is power in ONE example: a logger class Logger { private static _instance: MyClass; private constructor() { // initialisation... } public static getInstance() { return this._instance || (this._instance = new this()); } } const logger = Logger.getInstance();
  • 51. Creational Patterns Singleton pattern: There is power is ONE Global state Not garbage collected There for the entire life of the program * *Once lazy loaded Theoretically accessible from everywhere
  • 52. Resources Another take: The anti patterns http://www.laputan.org/mud/ Build your UML graphs with Lucid Charts https://www.lucidchart.com/pages/examples/uml_diagram_tool Readings Tools