SOLID Object Oriented Design
MD ABDUL HASIB
Today’s session
❑Review basic OOP and smells
❑SOLID principles
Basic OOP
❑Polymorphism
❑Encapsulation
❑Inheritance
❑Cohesion
❑Coupling
Cohesion and Coupling
❑Cohesion – How closely related are the
different responsibilities of a module
❑Coupling – How much one module relies on
another
❑Goal is low coupling and high cohesion
Refactoring code smells
❑Duplicate code
❑Long method
❑Large class
❑Temporary field
❑Switch statements
❑Parallel inheritance hierarchies
Design smells
❑Rigidity(Hard To Change)
▪Software is difficult to change
❑Fragility(Easy to break)
▪Program breaks in many places when a change
made in a single place
❑Immobility(Hard to reuse)
▪Parts could be useful in other systems, but effort
and risk to separate from original system is too
great
Design smells
❑Viscosity(Hard to do the right thing)
▪Design-preserving methods are more difficult to use than
the hacks
▪Development environment is slow and inefficient
❑Needless complexity
▪Contains elements that aren’t currently useful
❑Needless repetition
▪System has lots of repeated code elements
❑Opacity
▪A module is difficult to understand
SOLID
❑Single Responsibility Principle (SRP)
❑Open-Closed Principle (OCP)
❑Liskov Substitution Principle (LSP)
❑Interface Segregation Principle (ISP)
❑Dependency Inversion Principle (DIP)
Single Responsibility Principle (SRP)
A class should have
only one reason to
change
Responsibility
❑What a class does
❑The more a class does, the more likely it will
change
❑The more a class changes, the more likely we
will introduce bugs
EXAMPLE CODE
Single Responsibility Principle
Demo
❑Single Responsibility Principle
public final class UniqueIdGenerator {
static int uniqueId = 1;
private UniqueIdGenerator() {}
public static synchronized int getUniqueId() {return uniqueId++;}
}
public final class UniqueIdGenerator {
static int uniqueId = 1;
private UniqueIdGenerator() {}
public static synchronized int getUniqueId() {
return uniqueId++;
}
}
Open Closed principle (OCP)
Software entities (classes,
modules, functions, etc.)
should be open for
extension but closed for
modification
Bertrand Meyer is generally credited for having originated the term
open/closed principle,[2] which appeared in his 1988 book Object Oriented
Software Construction.
● A module will be said to be open if it is still available for extension.
For example, it should be possible to add fields to the data structures
it contains, or new elements to the set of functions it performs.
● A module will be said to be closed if it is available for use by other
modules. This assumes that the module has been given a well-
defined, stable description (the interface in the sense of information
hiding).
public void Parse(){
StringReader reader = new StringReader(scriptTextToProcess);
StringBuilder scope = new StringBuilder();
string line = reader.ReadLine();
while (line != null)
{
switch (line[0])
{
case '$':
// ……..
case '!':
// ……..
default:
// ……..
line = reader.ReadLine();
}}
Conforming to OCP
❑Open for extension
▪Behavior of the module can be extended
▪We are able to change what the module does
❑Closed for modification
▪Extending behavior does not result in changes to
source, binary, or code of the module
Does not conform to OCP
Client is not open and closed
Strategy pattern
Client is both open and closed
Conforming to OCP
❑Rely on abstractions
▪Interfaces
▪Abstract classes
EXAMPLE CODE
Open Closed Principle
Liskov Substitution Principle (LSP)
Subtypes must be
substitutable for
their base types
IS-A
❑Basic OOP discusses inheritance with “IS-A”
❑LSP says that “IS-A” refers to behavior
❑Behavior is what software is really all about
❑subtypes must be substitutable for their
base types
❑Substitutability : child class must not
remove base class behaviour
violate base class invariants(behaviour)
Substitution
❑Calling code should not know that one
module is different from its substitute
❑if ocp violation that invariably means LSp
violation
EXAMPLE CODE
Liskov Substitution Principle
EXAMPLE CODE
Liskov Substitution Principle
// Violation of Likov's Substitution Principle
class Rectangle
{
protected int m_width;
protected int m_height;
}
public int getArea(){
return m_width * m_height;
}
}
class Square extends Rectangle
{
}
class LspTest
{
private static Rectangle getNewRectangle()
{
return new Square();
}
public static void main (String args[])
{
Rectangle r = LspTest.getNewRectangle();
r.setWidth(5);
r.setHeight(10);
// user knows that r it's a rectangle.
// It assumes that he's able to set the width and height as for the base class
System.out.println(r.getArea());
// now he's surprised to see that the area is 100 instead of 50.
}
}
Interface Segregation Principle (ISP)
Clients should not be
forced to depend on
methods they do not use
EXAMPLE CODE
public Interface IReaderAndWriter {
public void read ();
public void write ();
}
Solution ??
EXAMPLE CODE
public Interface IReader{
public void read ();
}
public Interface IWriter {
public void write ();
}
Dependency Inversion Principle
(DIP)
❑High-level modules should not
depend on low-level modules. Both
should depend on abstractions
❑Abstractions should not depend on
details. Details should depend upon
abstractions
Abstraction dependency
The presence of abstractions to accomplish DIP have other design
implications in an Object Oriented program:
● All member variables in a class must be interfaces or abstracts.
● All concrete class packages must connect only through
interface/abstract classes packages.
● No class should derive from a concrete class.
● No method should override an implemented method.[5]
● All variable instantiation requires the implementation of a Creational
pattern as the Factory Method or the Factory pattern, or the more
complex use of a Dependency Injection framework.
Other principles
❑Keep It Simple Stupid (KISS)
❑You Ain’t Gonna Need It (YAGNI)
❑Don’t Repeat Yourself (DRY)
Questions?
Thank You

SOLID

  • 1.
    SOLID Object OrientedDesign MD ABDUL HASIB
  • 2.
    Today’s session ❑Review basicOOP and smells ❑SOLID principles
  • 3.
  • 4.
    Cohesion and Coupling ❑Cohesion– How closely related are the different responsibilities of a module ❑Coupling – How much one module relies on another ❑Goal is low coupling and high cohesion
  • 5.
    Refactoring code smells ❑Duplicatecode ❑Long method ❑Large class ❑Temporary field ❑Switch statements ❑Parallel inheritance hierarchies
  • 6.
    Design smells ❑Rigidity(Hard ToChange) ▪Software is difficult to change ❑Fragility(Easy to break) ▪Program breaks in many places when a change made in a single place ❑Immobility(Hard to reuse) ▪Parts could be useful in other systems, but effort and risk to separate from original system is too great
  • 7.
    Design smells ❑Viscosity(Hard todo the right thing) ▪Design-preserving methods are more difficult to use than the hacks ▪Development environment is slow and inefficient ❑Needless complexity ▪Contains elements that aren’t currently useful ❑Needless repetition ▪System has lots of repeated code elements ❑Opacity ▪A module is difficult to understand
  • 8.
    SOLID ❑Single Responsibility Principle(SRP) ❑Open-Closed Principle (OCP) ❑Liskov Substitution Principle (LSP) ❑Interface Segregation Principle (ISP) ❑Dependency Inversion Principle (DIP)
  • 10.
    Single Responsibility Principle(SRP) A class should have only one reason to change
  • 12.
    Responsibility ❑What a classdoes ❑The more a class does, the more likely it will change ❑The more a class changes, the more likely we will introduce bugs
  • 13.
  • 14.
    Demo ❑Single Responsibility Principle publicfinal class UniqueIdGenerator { static int uniqueId = 1; private UniqueIdGenerator() {} public static synchronized int getUniqueId() {return uniqueId++;} }
  • 15.
    public final classUniqueIdGenerator { static int uniqueId = 1; private UniqueIdGenerator() {} public static synchronized int getUniqueId() { return uniqueId++; } }
  • 16.
    Open Closed principle(OCP) Software entities (classes, modules, functions, etc.) should be open for extension but closed for modification
  • 18.
    Bertrand Meyer isgenerally credited for having originated the term open/closed principle,[2] which appeared in his 1988 book Object Oriented Software Construction. ● A module will be said to be open if it is still available for extension. For example, it should be possible to add fields to the data structures it contains, or new elements to the set of functions it performs. ● A module will be said to be closed if it is available for use by other modules. This assumes that the module has been given a well- defined, stable description (the interface in the sense of information hiding).
  • 19.
    public void Parse(){ StringReaderreader = new StringReader(scriptTextToProcess); StringBuilder scope = new StringBuilder(); string line = reader.ReadLine(); while (line != null) { switch (line[0]) { case '$': // …….. case '!': // …….. default: // …….. line = reader.ReadLine(); }}
  • 20.
    Conforming to OCP ❑Openfor extension ▪Behavior of the module can be extended ▪We are able to change what the module does ❑Closed for modification ▪Extending behavior does not result in changes to source, binary, or code of the module
  • 21.
    Does not conformto OCP Client is not open and closed
  • 22.
    Strategy pattern Client isboth open and closed
  • 23.
    Conforming to OCP ❑Relyon abstractions ▪Interfaces ▪Abstract classes
  • 24.
  • 25.
    Liskov Substitution Principle(LSP) Subtypes must be substitutable for their base types
  • 27.
    IS-A ❑Basic OOP discussesinheritance with “IS-A” ❑LSP says that “IS-A” refers to behavior ❑Behavior is what software is really all about ❑subtypes must be substitutable for their base types ❑Substitutability : child class must not remove base class behaviour violate base class invariants(behaviour)
  • 28.
    Substitution ❑Calling code shouldnot know that one module is different from its substitute ❑if ocp violation that invariably means LSp violation
  • 29.
  • 30.
    EXAMPLE CODE Liskov SubstitutionPrinciple // Violation of Likov's Substitution Principle class Rectangle { protected int m_width; protected int m_height; } public int getArea(){ return m_width * m_height; } }
  • 31.
    class Square extendsRectangle { } class LspTest { private static Rectangle getNewRectangle() { return new Square(); } public static void main (String args[]) { Rectangle r = LspTest.getNewRectangle(); r.setWidth(5); r.setHeight(10); // user knows that r it's a rectangle. // It assumes that he's able to set the width and height as for the base class System.out.println(r.getArea()); // now he's surprised to see that the area is 100 instead of 50. } }
  • 32.
    Interface Segregation Principle(ISP) Clients should not be forced to depend on methods they do not use
  • 34.
    EXAMPLE CODE public InterfaceIReaderAndWriter { public void read (); public void write (); } Solution ??
  • 35.
    EXAMPLE CODE public InterfaceIReader{ public void read (); } public Interface IWriter { public void write (); }
  • 36.
    Dependency Inversion Principle (DIP) ❑High-levelmodules should not depend on low-level modules. Both should depend on abstractions ❑Abstractions should not depend on details. Details should depend upon abstractions
  • 39.
    Abstraction dependency The presenceof abstractions to accomplish DIP have other design implications in an Object Oriented program: ● All member variables in a class must be interfaces or abstracts. ● All concrete class packages must connect only through interface/abstract classes packages. ● No class should derive from a concrete class. ● No method should override an implemented method.[5] ● All variable instantiation requires the implementation of a Creational pattern as the Factory Method or the Factory pattern, or the more complex use of a Dependency Injection framework.
  • 41.
    Other principles ❑Keep ItSimple Stupid (KISS) ❑You Ain’t Gonna Need It (YAGNI) ❑Don’t Repeat Yourself (DRY)
  • 42.
  • 43.