SlideShare a Scribd company logo
1 of 33
Download to read offline
Object Oriented Design Principles
–– class level
Xiao-Yan Chen
Beijing/July 13, 2007
2
Agenda
> Introduction
> OO Design Principles
> Evil Stuff and Anti-Patterns
3
Introduction
> Where we are?
Methodology and Design Tech
Process
Tools
Methodology
Design
technique
Heavyweight
process
Agile
process
Process
appraisal and improvement
For supporting
process
For supporting
methodology
For supporting
Design technique
4
Principles
> What is a bad design?
> The principles
• OCP open-closed principle
• SRP single responsibility principle
• ISP interface segregation principle
• LSP Liskov substitution principle
• DIP dependency inversion principle
> Principles reviewed
5
Bad designs
> Rigidity – hard to change
> Fragility – easy to break
> Immobility – hard to reuse
> Viscosity – hard to do the right thing
> Needless Complexity – over design
> Needless Repetition – error prone
> Opacity – hard to read and understand
6
Open Closed Principle
> Examples of OCP violation
public interface Shape extends Comparable{
public void draw();
}
public class Circle implements Shape {
public void draw() {
}
public int compareTo(Object o) {
if (o instanceof Rectangel) {
return -1;
}
else if (o instanceof Circle) {
return 0;
}
else {
return 1;
}
}
}
Shape
Circle Rectangle
New
Shape
7
Open Closed Principle
Software entities should be open for extension,
but closed for modification
B. Meyer, 1988
> Be open for extension
• module's behavior can be extended
> Be closed for modification
• source code for the module must not be changes
> Modules should be written so they can be extended without requiring
them to be modified
8
Open Closed Principle
> How to:
• Encapsulate what varies.
• Abstraction is the KEY.
• Use “Data-Driven” approaches.
> This principle implies that:
• Make all member variables private.
• No global variables.
• RTTI (Run-Time Type Information) is dangerous.
> Also:
• No significant program can be 100% closed.
• OK to take the first bullet.
9
Single Responsibility Principle
> Examples of SRP violation
Computational
Geometry
Application
Graphical
Application
GUI
Rectangle
draw()
area()
> This violation is bad for that:
• We must include the GUI in the Computational Geometry
application.
• If a change to the Graphical Application causes the Rectangle to
change, that change may force us to rebuild, retest, and redeploy
the Computational Geometry Application.
10
Single Responsibility Principle
> A Class should have one reason to change
• A Responsibility is a reason to change
> Single Responsibility = increased cohesion
> Not following results in needless dependencies
• More reasons to change.
• Rigidity, Immobility
11
Single Responsibility Principle
> Conform to SRP:
Computational
Geometry
Application
Graphical
Application
Rectangle
draw()
GUI
Geometric
Rectangle
area()
12
Interface Segregation Principle
13
Interface Segregation Principle
> Many client specific interfaces are better than one general
purpose interface
> Create an interface per client type not per client
• Avoid needless coupling to clients
GraphicalRect_I
draw()
Computational
Geometry
Application
Graphical
Application
Rectangle
draw()
area()
GUI
GeometricRect_I
Area()
14
Liskov Substitution Principle
“What is wanted here is something like the following
substitution property: If for each object o1 of type S there
is an object o2 of type T such that for all programs P
defined in terms of T, the behavior of P is unchanged
when o1 is substituted for o2 then S is a subtype of T.”
(Barbara Liskov, 1988)
15
Liskov Substitution Principle
> Any subclass should always be usable instead of its
parent class.
• Pre-conditions can only get weaker
• Post-conditions can only get stronger
> Derived classes should require no more and promise no
less.
16
Liskov Substitution Principle
public interface Bird{
public void fly();
}
public class Parrot implements Bird {
public void fly() {
System.out.println(“OK, I can fly.”);
}
}
public class Penguin implements Bird {
public void fly() {
throw new IllegalStateExeption(“Sorry, I can not fly…”);
}
}
>Example of LSP violation:
public class BirdCustomer {
……………..
Bird bird = new Parrot();
bird.fly();
……………..
……………..
bird = new Penguin();
bird.fly(); // oops, the customer will
be surprised!
…………….
…………….
}
17
Liskov Substitution Principle
public class Rectangle {
public void setWidth(double w) {
this.width = w;
}
public void setHeight(double h) {
this.height = h;
}
public double area() {
return this.width * this.height;
}
}
public class Square extends Rectangle {
public void setWidth(double w) {
super.setWidth(w);
super.setHeight(w);
}
public void setHeight(double h) {
super.setWidth(h);
super.setHeight(h);
}
}
>Example of LSP violation:
public class RectangleCustomer {
……………..
Rectangel rect = new Square();
rect.setWidth(4);
rect.setHeight(5);
assert rect.area()==20;// oops, the
customer will be surprised!
…………….
…………….
}
18
Liskov Substitution Principle
> IS-A (inheritance) relationship refers to the BEHAVIOR of
the class.
> BEHAVIOR = public members.
19
Dependency Inversion Principle
> Procedural layering: violation of DIP
Policy layer
Mechanism
layer
Utility layer
> Bad for:
• Transitive dependency
• Transitive change impacts
20
Dependency Inversion Principle
> A base class in an inheritance hierarchy should not know any of its
subclasses
> Modules with detailed implementations are not depended upon, but depend
themselves upon abstractions
> OCP states the goal; DIP states the mechanism;
> LSP is the insurance for DIP
I. High-level modules should not depend on low-level modules.
Both should depend on abstractions.
II. Abstractions should not depend on details.
Details should depend on abstractions
R. Martin, 1996
21
Dependency Inversion Principle
> OO layering: Conforming to DIP
Policy
Policy
Layer
Policy Service
Interface
Mechanism
Mechanism Layer
Mechanism Service
Interface
Utility
Utility
Layer
22
Dependency Inversion Principle
> This principle implies:
• Programming to interfaces, not implementations.
• Both the naming and the physical location of interfaces should
respect their customers, not their implementations.
• Dependency Injection.
Anyway, I need to depend on a concrete implementation object at
runtime, how can I get it?
23
Dependency Inversion Principle
> Dependency Injection:
• Don’t use new operator to instantiate a concrete class where
you need, instead inject it from outside.
> Dependency Injection options:
• Constructor Injection with PicoContainer
• Setter Injection with Spring
• Interface Injection
• Using a Service Locator
For details, refer to
http://www.martinfowler.com/articles/injection.html
24
OO Principles Reviewed
> Encapsulate what varies.
> Favor composition over inheritance.
> Program to interfaces, not implementations.
> Strive for loosely coupled designs between objects
that interact.
> Classes should be open for extension but closed for
modification.
> Depend on abstraction. Do not depend on concrete
classes.
> Only talk to your friends.
> Don’t call us, we’ll call you.
> A class should have only one reason to change.
Oh, what is this?
25
Law of Demeter
> Only talk to your friends, also known as “Law of
Demeter”.
> Only invoke methods that belong to:
• The object itself.
• Objects passes in as a parameter to the method.
• Any object the method creates or instantiates.
• Any components of the object. (objects directly referred to)
> Violating when you write a_object.m1().m2();
> Keep our circle of friends small  clear responsibility 
decrease complexity
> Law of Demeter for Concerns (LoDC) is good for Aspect
Oriented Software Development.
26
Agenda
> Introduction
> OO Design Principles
> Evil Stuff and Anti-Patterns
27
Evil Stuff
> Singletons / Global variables
• Singletons are actually OO global variables.
> Getters, Setters
• Evil for exposing information/implementation which should be hidden.
• Eliminate data movement. Data flow is procedure-oriented thinking.
• Don't ask for the information you need to do the work; ask the object that
has the information to do the work for you.
• Exceptions: computational query, get/set an interface
• http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-
toolbox.html?page=1
• http://www.javaworld.com/javaworld/jw-01-2004/jw-0102-toolbox.html
> Helper Classes
• Actually global procedures, hard to maintain.
• http://blogs.msdn.com/nickmalik/archive/2005/09/06/461404.aspx
• http://blogs.msdn.com/nickmalik/archive/2005/09/07/462054.aspx
28
Anti-Patterns
> Category
• Design related: The Blob, Poltergeist, Swiss Army Knife, Dead End
• Development related: Golden Hammer, Input Kludge
• Architecture related: Reinvent the wheel, Vendor lock-in
> The category:
• http://www.antipatterns.com/briefing/index.htm
• http://www.devx.com/Java/Article/29162
> Poltergeist:
http://www.icmgworld.com/corp/news/Articles/RS/jan_0302.asp
> Dead End:
http://www.icmgworld.com/corp/news/Articles/RS/jan_0402.asp
Much enough principles!
Tired of this session?
Here are some cookies 
30
Cookie – Thread Safe Singleton
public class Singleton {
private static Singleton instance = null;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
public class Singleton {
private volatile static Singleton instance = null;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
volatile can make the double-check singleton thread safe, but only since Java5.
31
Cookie – The dilemma of Observer
private class Model extends Observable {
public void handleAttributeChange(int value)
{
this.setChanged();
this.notifyObservers(value);
}
}
Observer observer = new Observer() {
public void update(Observable o, Object arg)
{
System.out.println(arg);
}
};
model.addObserver(observer)
new Thread() {
public void run() {
model.handleAttributeChange(1);
}
}.start();
new Thread() {
public void run() {
model.handleAttributeChange(2);
}
}.start();
Not thread safe, notifications to observers may be lost!
Notification order not guaranteed, early notification, maybe late received by observers.
32
Cookie – The dilemma of Observer
private class Model extends Observable {
public synchronized void
handleAttributeChange(int value) {
this.setChanged();
this.notifyObservers(value);
}
}
model.addObserver(observer);
final Object object = new Object();
Observer observer = new Observer() {
public void update(Observable o, Object arg) {
synchronized (object) {
System.out.println(arg);
}
}
};
model.addObserver(observer);
new Thread() {
public void run() {
synchronized (object) {
model.addObserver()
}
}
}.start();
model.handleAttributeChange(1);
Notifications will not be lost.
But, still not thread safe, dead-lock is permitted!
The End
Thank You!

More Related Content

What's hot

Implementing The Open/Closed Principle
Implementing The Open/Closed PrincipleImplementing The Open/Closed Principle
Implementing The Open/Closed PrincipleSam Hennessy
 
Geecon09: SOLID Design Principles
Geecon09: SOLID Design PrinciplesGeecon09: SOLID Design Principles
Geecon09: SOLID Design PrinciplesBruno Bossola
 
The Open Closed Principle - Part 1 - The Original Version
The Open Closed Principle - Part 1 - The Original VersionThe Open Closed Principle - Part 1 - The Original Version
The Open Closed Principle - Part 1 - The Original VersionPhilip Schwarz
 
Design Patterns: From STUPID to SOLID code
Design Patterns: From STUPID to SOLID codeDesign Patterns: From STUPID to SOLID code
Design Patterns: From STUPID to SOLID codePaulo Gandra de Sousa
 
S.O.L.I.D. Principles for Software Architects
S.O.L.I.D. Principles for Software ArchitectsS.O.L.I.D. Principles for Software Architects
S.O.L.I.D. Principles for Software ArchitectsRicardo Wilkins
 
Design principles - SOLID
Design principles - SOLIDDesign principles - SOLID
Design principles - SOLIDPranalee Rokde
 
Learning solid principles using c#
Learning solid principles using c#Learning solid principles using c#
Learning solid principles using c#Aditya Kumar Rajan
 
SOLID - Principles of Object Oriented Design
SOLID - Principles of Object Oriented DesignSOLID - Principles of Object Oriented Design
SOLID - Principles of Object Oriented DesignRiccardo Cardin
 
Advanced Object-Oriented/SOLID Principles
Advanced Object-Oriented/SOLID PrinciplesAdvanced Object-Oriented/SOLID Principles
Advanced Object-Oriented/SOLID PrinciplesJon Kruger
 
Lego For Engineers - Dependency Injection for LIDNUG (2011-06-03)
Lego For Engineers - Dependency Injection for LIDNUG (2011-06-03)Lego For Engineers - Dependency Injection for LIDNUG (2011-06-03)
Lego For Engineers - Dependency Injection for LIDNUG (2011-06-03)Theo Jungeblut
 
Solid principles
Solid principlesSolid principles
Solid principlesToan Nguyen
 
The good, the bad and the SOLID
The good, the bad and the SOLIDThe good, the bad and the SOLID
The good, the bad and the SOLIDFrikkie van Biljon
 
Refactoring to SOLID Code
Refactoring to SOLID CodeRefactoring to SOLID Code
Refactoring to SOLID CodeAdil Mughal
 
Contract First Development with Microsoft Code Contracts and Microsoft Pex at...
Contract First Development with Microsoft Code Contracts and Microsoft Pex at...Contract First Development with Microsoft Code Contracts and Microsoft Pex at...
Contract First Development with Microsoft Code Contracts and Microsoft Pex at...Theo Jungeblut
 
SOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principlesSOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principlesSergey Karpushin
 
Clean Code - Design Patterns and Best Practices at Silicon Valley Code Camp
Clean Code - Design Patterns and Best Practices at Silicon Valley Code CampClean Code - Design Patterns and Best Practices at Silicon Valley Code Camp
Clean Code - Design Patterns and Best Practices at Silicon Valley Code CampTheo Jungeblut
 

What's hot (20)

Binding android piece by piece
Binding android piece by pieceBinding android piece by piece
Binding android piece by piece
 
SOLID principles
SOLID principlesSOLID principles
SOLID principles
 
Implementing The Open/Closed Principle
Implementing The Open/Closed PrincipleImplementing The Open/Closed Principle
Implementing The Open/Closed Principle
 
Geecon09: SOLID Design Principles
Geecon09: SOLID Design PrinciplesGeecon09: SOLID Design Principles
Geecon09: SOLID Design Principles
 
The Open Closed Principle - Part 1 - The Original Version
The Open Closed Principle - Part 1 - The Original VersionThe Open Closed Principle - Part 1 - The Original Version
The Open Closed Principle - Part 1 - The Original Version
 
Design Patterns: From STUPID to SOLID code
Design Patterns: From STUPID to SOLID codeDesign Patterns: From STUPID to SOLID code
Design Patterns: From STUPID to SOLID code
 
S.O.L.I.D. Principles for Software Architects
S.O.L.I.D. Principles for Software ArchitectsS.O.L.I.D. Principles for Software Architects
S.O.L.I.D. Principles for Software Architects
 
Solid Principles
Solid PrinciplesSolid Principles
Solid Principles
 
Solid Principles
Solid PrinciplesSolid Principles
Solid Principles
 
Design principles - SOLID
Design principles - SOLIDDesign principles - SOLID
Design principles - SOLID
 
Learning solid principles using c#
Learning solid principles using c#Learning solid principles using c#
Learning solid principles using c#
 
SOLID - Principles of Object Oriented Design
SOLID - Principles of Object Oriented DesignSOLID - Principles of Object Oriented Design
SOLID - Principles of Object Oriented Design
 
Advanced Object-Oriented/SOLID Principles
Advanced Object-Oriented/SOLID PrinciplesAdvanced Object-Oriented/SOLID Principles
Advanced Object-Oriented/SOLID Principles
 
Lego For Engineers - Dependency Injection for LIDNUG (2011-06-03)
Lego For Engineers - Dependency Injection for LIDNUG (2011-06-03)Lego For Engineers - Dependency Injection for LIDNUG (2011-06-03)
Lego For Engineers - Dependency Injection for LIDNUG (2011-06-03)
 
Solid principles
Solid principlesSolid principles
Solid principles
 
The good, the bad and the SOLID
The good, the bad and the SOLIDThe good, the bad and the SOLID
The good, the bad and the SOLID
 
Refactoring to SOLID Code
Refactoring to SOLID CodeRefactoring to SOLID Code
Refactoring to SOLID Code
 
Contract First Development with Microsoft Code Contracts and Microsoft Pex at...
Contract First Development with Microsoft Code Contracts and Microsoft Pex at...Contract First Development with Microsoft Code Contracts and Microsoft Pex at...
Contract First Development with Microsoft Code Contracts and Microsoft Pex at...
 
SOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principlesSOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principles
 
Clean Code - Design Patterns and Best Practices at Silicon Valley Code Camp
Clean Code - Design Patterns and Best Practices at Silicon Valley Code CampClean Code - Design Patterns and Best Practices at Silicon Valley Code Camp
Clean Code - Design Patterns and Best Practices at Silicon Valley Code Camp
 

Viewers also liked

DHTML Prototyping: Silicon Valley Code Camp
DHTML Prototyping: Silicon Valley Code CampDHTML Prototyping: Silicon Valley Code Camp
DHTML Prototyping: Silicon Valley Code CampBill Scott
 
JavaServer Faces Anti-Patterns and Pitfalls
JavaServer Faces Anti-Patterns and PitfallsJavaServer Faces Anti-Patterns and Pitfalls
JavaServer Faces Anti-Patterns and PitfallsDennis Byrne
 
Mock Objects, Design and Dependency Inversion Principle
Mock Objects, Design and Dependency Inversion PrincipleMock Objects, Design and Dependency Inversion Principle
Mock Objects, Design and Dependency Inversion PrincipleP Heinonen
 
Introduction to Object Oriented Design
Introduction to Object Oriented DesignIntroduction to Object Oriented Design
Introduction to Object Oriented DesignComputing Cage
 
SOLID principles-Present
SOLID principles-PresentSOLID principles-Present
SOLID principles-PresentQuang Nguyen
 
Empathetic genre conversion exam prep
Empathetic genre conversion exam prepEmpathetic genre conversion exam prep
Empathetic genre conversion exam prepAndy Fisher
 
Object Oriented Design Principles
Object Oriented Design PrinciplesObject Oriented Design Principles
Object Oriented Design PrinciplesThang Tran Duc
 
Object Oriented Analysis and Design
Object Oriented Analysis and DesignObject Oriented Analysis and Design
Object Oriented Analysis and DesignAnirban Majumdar
 
Object Oriented Analysis and Design
Object Oriented Analysis and DesignObject Oriented Analysis and Design
Object Oriented Analysis and DesignHaitham El-Ghareeb
 

Viewers also liked (9)

DHTML Prototyping: Silicon Valley Code Camp
DHTML Prototyping: Silicon Valley Code CampDHTML Prototyping: Silicon Valley Code Camp
DHTML Prototyping: Silicon Valley Code Camp
 
JavaServer Faces Anti-Patterns and Pitfalls
JavaServer Faces Anti-Patterns and PitfallsJavaServer Faces Anti-Patterns and Pitfalls
JavaServer Faces Anti-Patterns and Pitfalls
 
Mock Objects, Design and Dependency Inversion Principle
Mock Objects, Design and Dependency Inversion PrincipleMock Objects, Design and Dependency Inversion Principle
Mock Objects, Design and Dependency Inversion Principle
 
Introduction to Object Oriented Design
Introduction to Object Oriented DesignIntroduction to Object Oriented Design
Introduction to Object Oriented Design
 
SOLID principles-Present
SOLID principles-PresentSOLID principles-Present
SOLID principles-Present
 
Empathetic genre conversion exam prep
Empathetic genre conversion exam prepEmpathetic genre conversion exam prep
Empathetic genre conversion exam prep
 
Object Oriented Design Principles
Object Oriented Design PrinciplesObject Oriented Design Principles
Object Oriented Design Principles
 
Object Oriented Analysis and Design
Object Oriented Analysis and DesignObject Oriented Analysis and Design
Object Oriented Analysis and Design
 
Object Oriented Analysis and Design
Object Oriented Analysis and DesignObject Oriented Analysis and Design
Object Oriented Analysis and Design
 

Similar to Object-oriented design principles

Improving the Design of Existing Software
Improving the Design of Existing SoftwareImproving the Design of Existing Software
Improving the Design of Existing SoftwareSteven Smith
 
The maze of Design Patterns & SOLID Principles
The maze of Design Patterns & SOLID PrinciplesThe maze of Design Patterns & SOLID Principles
The maze of Design Patterns & SOLID PrinciplesMuhammad Raza
 
Refactoring Applications using SOLID Principles
Refactoring Applications using SOLID PrinciplesRefactoring Applications using SOLID Principles
Refactoring Applications using SOLID PrinciplesSteven Smith
 
I gotta dependency on dependency injection
I gotta dependency on dependency injectionI gotta dependency on dependency injection
I gotta dependency on dependency injectionmhenroid
 
Improving The Quality of Existing Software
Improving The Quality of Existing SoftwareImproving The Quality of Existing Software
Improving The Quality of Existing SoftwareSteven Smith
 
Refactoring with SOLID - Telerik India DevCon 2013
Refactoring with SOLID - Telerik India DevCon 2013Refactoring with SOLID - Telerik India DevCon 2013
Refactoring with SOLID - Telerik India DevCon 2013Steven Smith
 
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
 
Dependency Injection in .NET applications
Dependency Injection in .NET applicationsDependency Injection in .NET applications
Dependency Injection in .NET applicationsBabak Naffas
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing SoftwareSteven Smith
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing SoftwareSteven Smith
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxanguraju1
 
Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016Steven Smith
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing SoftwareSteven Smith
 
Introduction to design_patterns
Introduction to design_patternsIntroduction to design_patterns
Introduction to design_patternsamitarcade
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingSteven Smith
 
Software design principles
Software design principlesSoftware design principles
Software design principlesMd.Mojibul Hoque
 

Similar to Object-oriented design principles (20)

Improving the Design of Existing Software
Improving the Design of Existing SoftwareImproving the Design of Existing Software
Improving the Design of Existing Software
 
The maze of Design Patterns & SOLID Principles
The maze of Design Patterns & SOLID PrinciplesThe maze of Design Patterns & SOLID Principles
The maze of Design Patterns & SOLID Principles
 
Refactoring Applications using SOLID Principles
Refactoring Applications using SOLID PrinciplesRefactoring Applications using SOLID Principles
Refactoring Applications using SOLID Principles
 
I gotta dependency on dependency injection
I gotta dependency on dependency injectionI gotta dependency on dependency injection
I gotta dependency on dependency injection
 
Improving The Quality of Existing Software
Improving The Quality of Existing SoftwareImproving The Quality of Existing Software
Improving The Quality of Existing Software
 
Design for Testability
Design for TestabilityDesign for Testability
Design for Testability
 
Refactoring with SOLID - Telerik India DevCon 2013
Refactoring with SOLID - Telerik India DevCon 2013Refactoring with SOLID - Telerik India DevCon 2013
Refactoring with SOLID - Telerik India DevCon 2013
 
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#
 
31 days Refactoring
31 days Refactoring31 days Refactoring
31 days Refactoring
 
Dependency Injection in .NET applications
Dependency Injection in .NET applicationsDependency Injection in .NET applications
Dependency Injection in .NET applications
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptx
 
L22 Design Principles
L22 Design PrinciplesL22 Design Principles
L22 Design Principles
 
Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 
Introduction to design_patterns
Introduction to design_patternsIntroduction to design_patterns
Introduction to design_patterns
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit Testing
 
Software design principles
Software design principlesSoftware design principles
Software design principles
 
AngularJS Basics
AngularJS BasicsAngularJS Basics
AngularJS Basics
 

Recently uploaded

MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...ranjana rawat
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingrknatarajan
 

Recently uploaded (20)

MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
 

Object-oriented design principles

  • 1. Object Oriented Design Principles –– class level Xiao-Yan Chen Beijing/July 13, 2007
  • 2. 2 Agenda > Introduction > OO Design Principles > Evil Stuff and Anti-Patterns
  • 3. 3 Introduction > Where we are? Methodology and Design Tech Process Tools Methodology Design technique Heavyweight process Agile process Process appraisal and improvement For supporting process For supporting methodology For supporting Design technique
  • 4. 4 Principles > What is a bad design? > The principles • OCP open-closed principle • SRP single responsibility principle • ISP interface segregation principle • LSP Liskov substitution principle • DIP dependency inversion principle > Principles reviewed
  • 5. 5 Bad designs > Rigidity – hard to change > Fragility – easy to break > Immobility – hard to reuse > Viscosity – hard to do the right thing > Needless Complexity – over design > Needless Repetition – error prone > Opacity – hard to read and understand
  • 6. 6 Open Closed Principle > Examples of OCP violation public interface Shape extends Comparable{ public void draw(); } public class Circle implements Shape { public void draw() { } public int compareTo(Object o) { if (o instanceof Rectangel) { return -1; } else if (o instanceof Circle) { return 0; } else { return 1; } } } Shape Circle Rectangle New Shape
  • 7. 7 Open Closed Principle Software entities should be open for extension, but closed for modification B. Meyer, 1988 > Be open for extension • module's behavior can be extended > Be closed for modification • source code for the module must not be changes > Modules should be written so they can be extended without requiring them to be modified
  • 8. 8 Open Closed Principle > How to: • Encapsulate what varies. • Abstraction is the KEY. • Use “Data-Driven” approaches. > This principle implies that: • Make all member variables private. • No global variables. • RTTI (Run-Time Type Information) is dangerous. > Also: • No significant program can be 100% closed. • OK to take the first bullet.
  • 9. 9 Single Responsibility Principle > Examples of SRP violation Computational Geometry Application Graphical Application GUI Rectangle draw() area() > This violation is bad for that: • We must include the GUI in the Computational Geometry application. • If a change to the Graphical Application causes the Rectangle to change, that change may force us to rebuild, retest, and redeploy the Computational Geometry Application.
  • 10. 10 Single Responsibility Principle > A Class should have one reason to change • A Responsibility is a reason to change > Single Responsibility = increased cohesion > Not following results in needless dependencies • More reasons to change. • Rigidity, Immobility
  • 11. 11 Single Responsibility Principle > Conform to SRP: Computational Geometry Application Graphical Application Rectangle draw() GUI Geometric Rectangle area()
  • 13. 13 Interface Segregation Principle > Many client specific interfaces are better than one general purpose interface > Create an interface per client type not per client • Avoid needless coupling to clients GraphicalRect_I draw() Computational Geometry Application Graphical Application Rectangle draw() area() GUI GeometricRect_I Area()
  • 14. 14 Liskov Substitution Principle “What is wanted here is something like the following substitution property: If for each object o1 of type S there is an object o2 of type T such that for all programs P defined in terms of T, the behavior of P is unchanged when o1 is substituted for o2 then S is a subtype of T.” (Barbara Liskov, 1988)
  • 15. 15 Liskov Substitution Principle > Any subclass should always be usable instead of its parent class. • Pre-conditions can only get weaker • Post-conditions can only get stronger > Derived classes should require no more and promise no less.
  • 16. 16 Liskov Substitution Principle public interface Bird{ public void fly(); } public class Parrot implements Bird { public void fly() { System.out.println(“OK, I can fly.”); } } public class Penguin implements Bird { public void fly() { throw new IllegalStateExeption(“Sorry, I can not fly…”); } } >Example of LSP violation: public class BirdCustomer { …………….. Bird bird = new Parrot(); bird.fly(); …………….. …………….. bird = new Penguin(); bird.fly(); // oops, the customer will be surprised! ……………. ……………. }
  • 17. 17 Liskov Substitution Principle public class Rectangle { public void setWidth(double w) { this.width = w; } public void setHeight(double h) { this.height = h; } public double area() { return this.width * this.height; } } public class Square extends Rectangle { public void setWidth(double w) { super.setWidth(w); super.setHeight(w); } public void setHeight(double h) { super.setWidth(h); super.setHeight(h); } } >Example of LSP violation: public class RectangleCustomer { …………….. Rectangel rect = new Square(); rect.setWidth(4); rect.setHeight(5); assert rect.area()==20;// oops, the customer will be surprised! ……………. ……………. }
  • 18. 18 Liskov Substitution Principle > IS-A (inheritance) relationship refers to the BEHAVIOR of the class. > BEHAVIOR = public members.
  • 19. 19 Dependency Inversion Principle > Procedural layering: violation of DIP Policy layer Mechanism layer Utility layer > Bad for: • Transitive dependency • Transitive change impacts
  • 20. 20 Dependency Inversion Principle > A base class in an inheritance hierarchy should not know any of its subclasses > Modules with detailed implementations are not depended upon, but depend themselves upon abstractions > OCP states the goal; DIP states the mechanism; > LSP is the insurance for DIP I. High-level modules should not depend on low-level modules. Both should depend on abstractions. II. Abstractions should not depend on details. Details should depend on abstractions R. Martin, 1996
  • 21. 21 Dependency Inversion Principle > OO layering: Conforming to DIP Policy Policy Layer Policy Service Interface Mechanism Mechanism Layer Mechanism Service Interface Utility Utility Layer
  • 22. 22 Dependency Inversion Principle > This principle implies: • Programming to interfaces, not implementations. • Both the naming and the physical location of interfaces should respect their customers, not their implementations. • Dependency Injection. Anyway, I need to depend on a concrete implementation object at runtime, how can I get it?
  • 23. 23 Dependency Inversion Principle > Dependency Injection: • Don’t use new operator to instantiate a concrete class where you need, instead inject it from outside. > Dependency Injection options: • Constructor Injection with PicoContainer • Setter Injection with Spring • Interface Injection • Using a Service Locator For details, refer to http://www.martinfowler.com/articles/injection.html
  • 24. 24 OO Principles Reviewed > Encapsulate what varies. > Favor composition over inheritance. > Program to interfaces, not implementations. > Strive for loosely coupled designs between objects that interact. > Classes should be open for extension but closed for modification. > Depend on abstraction. Do not depend on concrete classes. > Only talk to your friends. > Don’t call us, we’ll call you. > A class should have only one reason to change. Oh, what is this?
  • 25. 25 Law of Demeter > Only talk to your friends, also known as “Law of Demeter”. > Only invoke methods that belong to: • The object itself. • Objects passes in as a parameter to the method. • Any object the method creates or instantiates. • Any components of the object. (objects directly referred to) > Violating when you write a_object.m1().m2(); > Keep our circle of friends small  clear responsibility  decrease complexity > Law of Demeter for Concerns (LoDC) is good for Aspect Oriented Software Development.
  • 26. 26 Agenda > Introduction > OO Design Principles > Evil Stuff and Anti-Patterns
  • 27. 27 Evil Stuff > Singletons / Global variables • Singletons are actually OO global variables. > Getters, Setters • Evil for exposing information/implementation which should be hidden. • Eliminate data movement. Data flow is procedure-oriented thinking. • Don't ask for the information you need to do the work; ask the object that has the information to do the work for you. • Exceptions: computational query, get/set an interface • http://www.javaworld.com/javaworld/jw-09-2003/jw-0905- toolbox.html?page=1 • http://www.javaworld.com/javaworld/jw-01-2004/jw-0102-toolbox.html > Helper Classes • Actually global procedures, hard to maintain. • http://blogs.msdn.com/nickmalik/archive/2005/09/06/461404.aspx • http://blogs.msdn.com/nickmalik/archive/2005/09/07/462054.aspx
  • 28. 28 Anti-Patterns > Category • Design related: The Blob, Poltergeist, Swiss Army Knife, Dead End • Development related: Golden Hammer, Input Kludge • Architecture related: Reinvent the wheel, Vendor lock-in > The category: • http://www.antipatterns.com/briefing/index.htm • http://www.devx.com/Java/Article/29162 > Poltergeist: http://www.icmgworld.com/corp/news/Articles/RS/jan_0302.asp > Dead End: http://www.icmgworld.com/corp/news/Articles/RS/jan_0402.asp
  • 29. Much enough principles! Tired of this session? Here are some cookies 
  • 30. 30 Cookie – Thread Safe Singleton public class Singleton { private static Singleton instance = null; private Singleton() { } public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } } public class Singleton { private volatile static Singleton instance = null; private Singleton() { } public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } } volatile can make the double-check singleton thread safe, but only since Java5.
  • 31. 31 Cookie – The dilemma of Observer private class Model extends Observable { public void handleAttributeChange(int value) { this.setChanged(); this.notifyObservers(value); } } Observer observer = new Observer() { public void update(Observable o, Object arg) { System.out.println(arg); } }; model.addObserver(observer) new Thread() { public void run() { model.handleAttributeChange(1); } }.start(); new Thread() { public void run() { model.handleAttributeChange(2); } }.start(); Not thread safe, notifications to observers may be lost! Notification order not guaranteed, early notification, maybe late received by observers.
  • 32. 32 Cookie – The dilemma of Observer private class Model extends Observable { public synchronized void handleAttributeChange(int value) { this.setChanged(); this.notifyObservers(value); } } model.addObserver(observer); final Object object = new Object(); Observer observer = new Observer() { public void update(Observable o, Object arg) { synchronized (object) { System.out.println(arg); } } }; model.addObserver(observer); new Thread() { public void run() { synchronized (object) { model.addObserver() } } }.start(); model.handleAttributeChange(1); Notifications will not be lost. But, still not thread safe, dead-lock is permitted!