SlideShare a Scribd company logo
PRINCIPLES OF OBJECT ORIENTED CLASS DESIGN




                             By:
                             NEETU MISHRA
Agenda
Principles of class design (aka SOLID principles):

•   Single Responsibility Principle (SRP)
•   Open Closed Principle (OCP)
•   Liskov Substitution Principle (LSP)
•   Interface Segregation Principle (ISP)
•   Dependency Inversion Principle (DIP)
What do you mean by a good class
design??
Good class design
• Represents any real world entity

• Better code readability/ understanding

• Loosely coupled with other classes

• Compact & Optimized

• Easily testable
Single Responsibility Principle (SRP)

• One responsibility.

• One, and only one, reason to change.

• Change in the class should not force
  programmers to change into other classes.

• BankAccount class- Example
Single Responsibility Principle (SRP) - Example

Class BankAccount{
  private double bal; //setters & getters
  public String getCurrentBalanceInRupees (){…}
  public String getCurrentBalanceInUSD(){…}
  public double getBalance(){
      //return balance in round figures upto 2 decimals}
  public double debit (double amount){…}
      //how to handle diff.currency addition
  public double credit (double amount){…}
  //so on
}
Single Responsibility Principle (SRP)-Responsibility


• Responsibility of Bank Account class
  ▫   Currency conversion
  ▫   Checking currency for addition & subtraction
  ▫   Rounding-off the balance
  ▫   Debit the amount
  ▫   Credit the amount
  ▫   Details of account holder
  ▫   Transaction history
  ▫   //so on…
Single Responsibility Principle (SRP) - Solution

Class Money{
  private double value;
  private String currencyType; //setters & getters
  public double getValue (){
      //convert money value according to currencyType
      // class currency converter
      //round-off value upto 2 decimals
  }
  public double addMoney(Money amount){…}
  public double subtractMoney(Money amount){…}
}
Single Responsibility Principle (SRP) - Solution

Class BankAccount{
  private Money balance; //setters & getters
  public double getBalance (){…}
  public double debit (Money amount){
      //call balance.addMoney(amount)…}
  public double credit (Money amount){
      //call balance.subtractMoney(amount)…}
}
Single Responsibility Principle (SRP)-Responsibility


• Responsibility division for BankAccount class
  ▫ CurrencyConverter Class – Currency conversion
  ▫ Money Class – Check currency for addition or
    subtraction
  ▫ BankAccount class – Debit/Credit the amount
  ▫ Details of account holder – Person class
  ▫ Transaction history – TransactionHistory class
  ▫ //so on…
Single Responsibility Principle (SRP)


• Any Questions on SRP???
So, What is Single Responsibility Principle (SRP)?
Open Closed Principle (OCP)
• Open for Extension and closed for Modification.

• Don’t change existing code or classes.

• Add new functionality by adding new subclasses or
  methods, or by reusing existing code through delegation.

Advantage:
• Prevents you from introducing new bugs in existing
  code.
Open Closed Principle (OCP) - Example
Polymorphism for conforming to the OCP:

void LogOn (Modem m, string user, string pw)
{
    if (m instanceOf Hayes)
       DialHayes((Hayes)m, user);

    else if (m instanceOf courrier)
       DialCourrier((Courrier)m, user);

    else if (m instanceOf ernie)
       DialErnie((Ernie)m, user)
    // ...so on
}
Open Closed Principle (OCP) - Example
 Consider the class design something like this:




  Here LogOn has been closed for modification.
Open Closed Principle (OCP) - Example
Abstract Class Modem{
  Void Dial(String s);
  Void send(Char c);
  Char recv();
  Void HangUp();
  Void LogOn(Modem m, string user, string pw)) {
       m.Dial();
  }
}

Here LogOn method conforms to the OCP. Its behavior can be
 extended without modifying it.
Open Closed Principle (OCP)

Goals of OCP:

• Create modules that are extensible, without being
  changed.

• Use Unit tests if you are adding in the existing code
Open Closed Principle (OCP)

Any questions??
So, What is Open Closed Principle (OCP)??
Liskov Substitution Principle (LSP)

The LSP applies to inheritance hierarchies.

• It specifies that you should design your classes so that client
  dependencies can be substituted with subclasses.
• All subclasses must, therefore, operate the same manner as their
  base classes.
• The specific functionality of the subclass may be different but must
  conform to the expected behavior of the base class.
• To be a true behavioral subtype, the subclass must not only
  implement the base class' methods and properties but also conform
  to its implied behavior.
Liskov Substitution Principle (LSP)
It helps to get answers of following questions:

• Provides the design rules that govern the particular use
  of inheritance.

• Characteristics of the best inheritance hierarchies
Liskov Substitution Principle (LSP) - Definition
• If for each object o1 of type S
  S o1 = new S();

and,

  there is an object o2 of type T
  T o2 = new 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.
Liskov Substitution Principle (LSP)
• Subtypes must be substitutable for their base types.


• In simpler version,
  ▫ Functions that use pointers or references to base classes
    must be able to use objects of derived classes without
    knowing it.

The canonical example is the Rectangle/Square dilemma.
Liskov Substitution Principle (LSP)
Class Rectangle{
  int length, breadth;
  void setLength(){…}
  void setBreadth(){…}
}
Class Square extends Rectangle{
  void setLength(int a){ // similarly for setBreadth
      Super.setLength(a);
      Super.setBreadth(a);
  }
  }
Liskov Substitution Principle (LSP)


Consider the following function:

void func(Rectangle r){
     r.SetLength(20);
     r.SetBreadth(32);
}
Liskov Substitution Principle (LSP)
• Ugly fix for LSP violation for Rectangle & Square

 void f(Shape shape){
     If(shape instanceOf Rectangle){
       //call funcForRectangle();
     } else {
        //call funcForSquare();
     }
 }
 which rule is violating here??
Liskov Substitution Principle (LSP)
 Thus, violations of LSP are latent violations of OCP.
Why is the LSP important?

• Because if not, then class hierarchies would be a
  mess.
  ▫ Mess being that whenever a subclass instance was
    passed as parameter to any method, strange
    behavior would occur.

• It provides the design rules that govern the particular
  use of inheritance, and Characteristics of the best
  inheritance hierarchies
Liskov Substitution Principle (LSP)

• Any Questions on LSP???
So, What is Liskov Substitution Principle (LSP)??
Interface Segregation Principle (ISP)

• Many client specific interfaces are better than one
  general purpose interface.

• The clients should not be forced to implement interfaces
  they don't use.
  ▫ Instead of one fat interface many small interfaces are
    preferred based on groups of methods, each one serving one
    sub-module.
Interface Segregation Principle (ISP)
The methods needed by each client are placed in single interface that are
specific to the client.




               Fat Service with Integrated Interfaces
Interface Segregation Principle (ISP)
The methods needed by each client are placed in special interfaces that are
specific to that client.




                       Segregated Interfaces
Interface Segregation Principle (ISP)

How would you handle if two clients have some common
 methods?

Something like:

Client A – method1, method2, method3, method4
  &
Client B – method1 , method2, method5, method6
Interface Segregation Principle (ISP) - Example

• Manager class – Represent the person which manages the workers.

• 2 types of workers – They can work & need daily lunch break to eat.
  ▫ some average, and
  ▫ some very efficient workers.

• But now some robots came in the company they work as well , but
  they don't eat so they don't need a lunch break.

• One on side the new Robot class need to implement the IWorker
  interface (work() & eat()) because robot works. On the other side,
  the don't have to implement it because they don't eat.
Interface Segregation Principle (ISP) - Example

// interface segregation principle - bad example

interface IWorker {
    public void work();
    public void eat();
}
class Worker implements IWorker{
    public void work() {
      // ....working
    }
    public void eat() {
      // ...... eating in lunch break
    }
}
Interface Segregation Principle (ISP) - Example

class SuperWorker implements IWorker{
    public void work() { //.... working much more}
    public void eat() { //.... eating in lunch break}
}

class Manager {
    IWorker worker;
    public void setWorker(IWorker w) {
      worker=w;
    }
    public void manage() {
      worker.work();
    }
}
Interface Segregation Principle (ISP) - Solution

// interface segregation principle - good example

interface IWorkable {
    public void work();
}

interface IEatable{
    public void eat();
}
Interface Segregation Principle (ISP) - Solution

class Worker implements IWorkable, IEatable{
    public void work() {
      // ....working
    }
    public void eat() {
      // ...... eating in launch break
    }
}

class SuperWorker implements IWorkable, IEatable{
    public void work() { //.... working much more}
    public void eat() { //.... eating in launch break}
}
Interface Segregation Principle (ISP) - Solution

class Robot implements IWorkable {
    public void work() { //.... working}
}

class Manager {
    IWorkable worker;
    public void setWorker(IWorkable w) {
      worker=w;
    }
    public void manage() {
      worker.work();
    }
}
Interface Segregation Principle (ISP)


Any Questions??
So, What is Interface Segregation Principle (ISP)?
Dependency Inversion Principle (DIP)

• Depend upon Abstractions. Do not depend upon
  concretions.

• In other words, it is the strategy of depending upon
  interfaces or abstract functions & classes, rather than
  upon concrete functions & classes.

• High level modules should not depend upon low-level
  modules. Both should depend upon abstractions.
Dependency Inversion Principle (DIP) - Example

Example: ATM & Bank Account

Class ATM{
  private BankAccount ba = new BankAccount();
  public String displayBalance(){
      return “ Your balance is: ” + ba.currentBalance();
  }
}
Dependency Inversion Principle (DIP) - Example


Class BankAccount{
  private Double bal; //setters & getters
  public String currentBalance (){
      return bal.toString();
  }
}
Dependency Inversion Principle (DIP) - Solution

Solution: Use Interfaces

  Because the dependency of one class to another one
  should depend on the smallest possible interface.
Dependency Inversion Principle (DIP) - Solution

1) BankAccount Interface
Public Interface BankAccount{
      public String currentBalance ();
}

2) StubBankAccount class
Class StubBankAccount implements BankAccount{
      public String currentBalance (){
             return “3000”;
      }
}
Dependency Inversion Principle (DIP) - Solution

3) Implementation of BankAccount class

Class BankAccountImpl implements BankAccount
{
      public String currentBalance (){
             Your balance is: ” + ba.currentBalance();
      }
}
Dependency Inversion Principle (DIP) - Solution

4) Class ATM{

    private BankAccount ba;
    ATM(BankAccount ba){
        this.ba = ba;
    }
    public String displayBalance(){
        return “ Your balance is: ” + ba.currentBalance();
    }
}
Dependency Inversion Principle (DIP) - Solution

5) Class ATMTest{

    @Test
    public void shouldDisplayTheBalance(){
        StubBankAccount sba = new StubBankAccount();
       ATM atm = new ATM(sba);
       assertEquals( “ Your balance is: 3000”,
               atm.displaybalance());
    }
}
Dependency Inversion Principle (DIP) - Solution

5) Class SomeClassUsingATM{

     BankAccountImpl ba = new BankAccountImpl();
     ATM atm = new ATM(ba);
     sopln (atm.displayBalance());

}
Dependency Inversion Principle (DIP)
• What Inversion means in DIP??
  ▫ It is primarily about reversing the conventional direction
    of dependencies from "higher level" components to "lower
    level" components such that "lower level" components are
    dependent upon the interfaces owned by the "higher level"
    components.
Dependency Inversion Principle (DIP) - Advantage

• Choose which implementation is better suited for your
  particular environment
  • Either at compile time in the application, or
  • At the runtime by configuration.

• Simplifies the unit testing.

• Loosely coupled design.
Inversion Of Control (IOC)

• Inversion of Control is a design pattern where an Objects
  gets handed its dependency by an outside framework,
  rather than asking a framework for its dependency.

• The benefits of IoC are:
  ▫ You have no dependency on a central framework, so this
    can be changed if desired.
  ▫ Since objects are created by injection, preferably using
    interfaces, it's easy to create unit tests that replace
    dependencies with mock versions.
  ▫ Decoupling off code.
Inversion Of Control (IOC)

• The "inversion" in DIP is not the same as in Inversion of
  Control.
  ▫ The first one is about compile-time dependencies,
    while the second one is about the flow of control between
    methods at runtime.
Dependency Inversion Principle (DIP)


• Any Questions on DIP???
So, What is Dependency Inversion Principle (DIP)?
Summary
Principles of class design (aka SOLID):

• Single Responsibility Principle (SRP)
  ▫ Create as many classes you want but
      They should follow some real world entity
      And have single responsibility
• Open Closed Principle (OCP)
  ▫ Open for Extension, Closed for Modification
Summary

• Liskov Substitution Principle (LSP)
  ▫ Object of derived class can be passed instead of
    object of base class without changing the behavior
    of program.
• Interface Segregation Principle (ISP)
  ▫ Create multiple client specific interface rather
    than creating single interface for multiple clients.
Summary

• Dependency Inversion Principle (DIP)
  ▫ It is the strategy of depending upon interfaces or abstract
    functions and classes, rather than upon concrete functions
    and classes
Bibliography
• http://
  www.objectmentor.com/omSolutions/oops_what.htm

• http://c2.com/cgi/wiki?PrinciplesOfObjectOrientedD
Questions??
Thank You

More Related Content

PPTX
Solid principles
KEY
Solid principles
PPTX
Solid principles
PPTX
Design principles - SOLID
PPT
SOLID Design Principles
PDF
Solid Principles
PDF
Introduction to SOLID Principles
PPTX
Clean code: SOLID
Solid principles
Solid principles
Solid principles
Design principles - SOLID
SOLID Design Principles
Solid Principles
Introduction to SOLID Principles
Clean code: SOLID

What's hot (20)

PDF
Liscov substitution principle
PPTX
Learning solid principles using c#
PPTX
java 8 new features
PDF
Node Architecture and Getting Started with Express
PPTX
An Introduction To REST API
PDF
SOLID Design Principles applied in Java
PPTX
SOLID principles
PDF
Java 8 features
PDF
TypeScript - An Introduction
PPTX
SOLID Principles
PPTX
Java Spring Framework
PPT
Oops concepts in php
PDF
JavaScript Promises
KEY
SOLID Design Principles
PPTX
Exception Handling in Java
PPTX
Express js
PDF
JPA and Hibernate
PPTX
Advance Java Topics (J2EE)
PPTX
Core java complete ppt(note)
Liscov substitution principle
Learning solid principles using c#
java 8 new features
Node Architecture and Getting Started with Express
An Introduction To REST API
SOLID Design Principles applied in Java
SOLID principles
Java 8 features
TypeScript - An Introduction
SOLID Principles
Java Spring Framework
Oops concepts in php
JavaScript Promises
SOLID Design Principles
Exception Handling in Java
Express js
JPA and Hibernate
Advance Java Topics (J2EE)
Core java complete ppt(note)
Ad

Viewers also liked (10)

PPT
OO design principles & heuristics
PDF
SOLID design principles applied in Java
PDF
Mock Objects, Design and Dependency Inversion Principle
PDF
SOLID mit Java 8
PDF
Object-oriented design principles
PDF
Design for Testability
PPTX
Implementing The Open/Closed Principle
PDF
SOLID Principles and Design Patterns
PPTX
Principles of object oriented programming
PPTX
List of Software Development Model and Methods
OO design principles & heuristics
SOLID design principles applied in Java
Mock Objects, Design and Dependency Inversion Principle
SOLID mit Java 8
Object-oriented design principles
Design for Testability
Implementing The Open/Closed Principle
SOLID Principles and Design Patterns
Principles of object oriented programming
List of Software Development Model and Methods
Ad

Similar to principles of object oriented class design (20)

PPTX
Object Oriented Principle’s
PDF
Understanding SOLID Principles in OOP programming
PDF
L22 Design Principles
PPT
DesignPrinciples-and-DesignPatterns
PDF
Solid principles - Object oriendte
PPTX
L07 Design Principles
PDF
Solid principles
PPTX
Solid Principles
PPTX
Solid principles
PDF
Clean Code�Chapter 3. (1)
PPTX
Sec1_SOLID Principles_Software Engineering.pptx
PPTX
SOLID Principles
PPTX
SOLID Principles in OOPS ooooooooo.pptx
PPTX
Soild principles
PPTX
An ultimate guide to SOLID Principles, developers must know.
PPTX
Object Oriented Design SOLID Principles
PPTX
OO Design Principles
PPTX
Design principle vs design patterns
PDF
Inversion of Control
PDF
Solid Principle
Object Oriented Principle’s
Understanding SOLID Principles in OOP programming
L22 Design Principles
DesignPrinciples-and-DesignPatterns
Solid principles - Object oriendte
L07 Design Principles
Solid principles
Solid Principles
Solid principles
Clean Code�Chapter 3. (1)
Sec1_SOLID Principles_Software Engineering.pptx
SOLID Principles
SOLID Principles in OOPS ooooooooo.pptx
Soild principles
An ultimate guide to SOLID Principles, developers must know.
Object Oriented Design SOLID Principles
OO Design Principles
Design principle vs design patterns
Inversion of Control
Solid Principle

Recently uploaded (20)

PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
KodekX | Application Modernization Development
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Encapsulation theory and applications.pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
cuic standard and advanced reporting.pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
Digital-Transformation-Roadmap-for-Companies.pptx
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
KodekX | Application Modernization Development
Advanced methodologies resolving dimensionality complications for autism neur...
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Mobile App Security Testing_ A Comprehensive Guide.pdf
Encapsulation theory and applications.pdf
Per capita expenditure prediction using model stacking based on satellite ima...
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Spectral efficient network and resource selection model in 5G networks
Chapter 3 Spatial Domain Image Processing.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
20250228 LYD VKU AI Blended-Learning.pptx
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
NewMind AI Monthly Chronicles - July 2025
cuic standard and advanced reporting.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
“AI and Expert System Decision Support & Business Intelligence Systems”

principles of object oriented class design

  • 1. PRINCIPLES OF OBJECT ORIENTED CLASS DESIGN By: NEETU MISHRA
  • 2. Agenda Principles of class design (aka SOLID principles): • Single Responsibility Principle (SRP) • Open Closed Principle (OCP) • Liskov Substitution Principle (LSP) • Interface Segregation Principle (ISP) • Dependency Inversion Principle (DIP)
  • 3. What do you mean by a good class design??
  • 4. Good class design • Represents any real world entity • Better code readability/ understanding • Loosely coupled with other classes • Compact & Optimized • Easily testable
  • 5. Single Responsibility Principle (SRP) • One responsibility. • One, and only one, reason to change. • Change in the class should not force programmers to change into other classes. • BankAccount class- Example
  • 6. Single Responsibility Principle (SRP) - Example Class BankAccount{ private double bal; //setters & getters public String getCurrentBalanceInRupees (){…} public String getCurrentBalanceInUSD(){…} public double getBalance(){ //return balance in round figures upto 2 decimals} public double debit (double amount){…} //how to handle diff.currency addition public double credit (double amount){…} //so on }
  • 7. Single Responsibility Principle (SRP)-Responsibility • Responsibility of Bank Account class ▫ Currency conversion ▫ Checking currency for addition & subtraction ▫ Rounding-off the balance ▫ Debit the amount ▫ Credit the amount ▫ Details of account holder ▫ Transaction history ▫ //so on…
  • 8. Single Responsibility Principle (SRP) - Solution Class Money{ private double value; private String currencyType; //setters & getters public double getValue (){ //convert money value according to currencyType // class currency converter //round-off value upto 2 decimals } public double addMoney(Money amount){…} public double subtractMoney(Money amount){…} }
  • 9. Single Responsibility Principle (SRP) - Solution Class BankAccount{ private Money balance; //setters & getters public double getBalance (){…} public double debit (Money amount){ //call balance.addMoney(amount)…} public double credit (Money amount){ //call balance.subtractMoney(amount)…} }
  • 10. Single Responsibility Principle (SRP)-Responsibility • Responsibility division for BankAccount class ▫ CurrencyConverter Class – Currency conversion ▫ Money Class – Check currency for addition or subtraction ▫ BankAccount class – Debit/Credit the amount ▫ Details of account holder – Person class ▫ Transaction history – TransactionHistory class ▫ //so on…
  • 11. Single Responsibility Principle (SRP) • Any Questions on SRP???
  • 12. So, What is Single Responsibility Principle (SRP)?
  • 13. Open Closed Principle (OCP) • Open for Extension and closed for Modification. • Don’t change existing code or classes. • Add new functionality by adding new subclasses or methods, or by reusing existing code through delegation. Advantage: • Prevents you from introducing new bugs in existing code.
  • 14. Open Closed Principle (OCP) - Example Polymorphism for conforming to the OCP: void LogOn (Modem m, string user, string pw) { if (m instanceOf Hayes) DialHayes((Hayes)m, user); else if (m instanceOf courrier) DialCourrier((Courrier)m, user); else if (m instanceOf ernie) DialErnie((Ernie)m, user) // ...so on }
  • 15. Open Closed Principle (OCP) - Example Consider the class design something like this: Here LogOn has been closed for modification.
  • 16. Open Closed Principle (OCP) - Example Abstract Class Modem{ Void Dial(String s); Void send(Char c); Char recv(); Void HangUp(); Void LogOn(Modem m, string user, string pw)) { m.Dial(); } } Here LogOn method conforms to the OCP. Its behavior can be extended without modifying it.
  • 17. Open Closed Principle (OCP) Goals of OCP: • Create modules that are extensible, without being changed. • Use Unit tests if you are adding in the existing code
  • 18. Open Closed Principle (OCP) Any questions??
  • 19. So, What is Open Closed Principle (OCP)??
  • 20. Liskov Substitution Principle (LSP) The LSP applies to inheritance hierarchies. • It specifies that you should design your classes so that client dependencies can be substituted with subclasses. • All subclasses must, therefore, operate the same manner as their base classes. • The specific functionality of the subclass may be different but must conform to the expected behavior of the base class. • To be a true behavioral subtype, the subclass must not only implement the base class' methods and properties but also conform to its implied behavior.
  • 21. Liskov Substitution Principle (LSP) It helps to get answers of following questions: • Provides the design rules that govern the particular use of inheritance. • Characteristics of the best inheritance hierarchies
  • 22. Liskov Substitution Principle (LSP) - Definition • If for each object o1 of type S S o1 = new S(); and, there is an object o2 of type T T o2 = new 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.
  • 23. Liskov Substitution Principle (LSP) • Subtypes must be substitutable for their base types. • In simpler version, ▫ Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it. The canonical example is the Rectangle/Square dilemma.
  • 24. Liskov Substitution Principle (LSP) Class Rectangle{ int length, breadth; void setLength(){…} void setBreadth(){…} } Class Square extends Rectangle{ void setLength(int a){ // similarly for setBreadth Super.setLength(a); Super.setBreadth(a); } }
  • 25. Liskov Substitution Principle (LSP) Consider the following function: void func(Rectangle r){ r.SetLength(20); r.SetBreadth(32); }
  • 26. Liskov Substitution Principle (LSP) • Ugly fix for LSP violation for Rectangle & Square void f(Shape shape){ If(shape instanceOf Rectangle){ //call funcForRectangle(); } else { //call funcForSquare(); } } which rule is violating here??
  • 27. Liskov Substitution Principle (LSP) Thus, violations of LSP are latent violations of OCP.
  • 28. Why is the LSP important? • Because if not, then class hierarchies would be a mess. ▫ Mess being that whenever a subclass instance was passed as parameter to any method, strange behavior would occur. • It provides the design rules that govern the particular use of inheritance, and Characteristics of the best inheritance hierarchies
  • 29. Liskov Substitution Principle (LSP) • Any Questions on LSP???
  • 30. So, What is Liskov Substitution Principle (LSP)??
  • 31. Interface Segregation Principle (ISP) • Many client specific interfaces are better than one general purpose interface. • The clients should not be forced to implement interfaces they don't use. ▫ Instead of one fat interface many small interfaces are preferred based on groups of methods, each one serving one sub-module.
  • 32. Interface Segregation Principle (ISP) The methods needed by each client are placed in single interface that are specific to the client. Fat Service with Integrated Interfaces
  • 33. Interface Segregation Principle (ISP) The methods needed by each client are placed in special interfaces that are specific to that client. Segregated Interfaces
  • 34. Interface Segregation Principle (ISP) How would you handle if two clients have some common methods? Something like: Client A – method1, method2, method3, method4 & Client B – method1 , method2, method5, method6
  • 35. Interface Segregation Principle (ISP) - Example • Manager class – Represent the person which manages the workers. • 2 types of workers – They can work & need daily lunch break to eat. ▫ some average, and ▫ some very efficient workers. • But now some robots came in the company they work as well , but they don't eat so they don't need a lunch break. • One on side the new Robot class need to implement the IWorker interface (work() & eat()) because robot works. On the other side, the don't have to implement it because they don't eat.
  • 36. Interface Segregation Principle (ISP) - Example // interface segregation principle - bad example interface IWorker { public void work(); public void eat(); } class Worker implements IWorker{ public void work() { // ....working } public void eat() { // ...... eating in lunch break } }
  • 37. Interface Segregation Principle (ISP) - Example class SuperWorker implements IWorker{ public void work() { //.... working much more} public void eat() { //.... eating in lunch break} } class Manager { IWorker worker; public void setWorker(IWorker w) { worker=w; } public void manage() { worker.work(); } }
  • 38. Interface Segregation Principle (ISP) - Solution // interface segregation principle - good example interface IWorkable { public void work(); } interface IEatable{ public void eat(); }
  • 39. Interface Segregation Principle (ISP) - Solution class Worker implements IWorkable, IEatable{ public void work() { // ....working } public void eat() { // ...... eating in launch break } } class SuperWorker implements IWorkable, IEatable{ public void work() { //.... working much more} public void eat() { //.... eating in launch break} }
  • 40. Interface Segregation Principle (ISP) - Solution class Robot implements IWorkable { public void work() { //.... working} } class Manager { IWorkable worker; public void setWorker(IWorkable w) { worker=w; } public void manage() { worker.work(); } }
  • 41. Interface Segregation Principle (ISP) Any Questions??
  • 42. So, What is Interface Segregation Principle (ISP)?
  • 43. Dependency Inversion Principle (DIP) • Depend upon Abstractions. Do not depend upon concretions. • In other words, it is the strategy of depending upon interfaces or abstract functions & classes, rather than upon concrete functions & classes. • High level modules should not depend upon low-level modules. Both should depend upon abstractions.
  • 44. Dependency Inversion Principle (DIP) - Example Example: ATM & Bank Account Class ATM{ private BankAccount ba = new BankAccount(); public String displayBalance(){ return “ Your balance is: ” + ba.currentBalance(); } }
  • 45. Dependency Inversion Principle (DIP) - Example Class BankAccount{ private Double bal; //setters & getters public String currentBalance (){ return bal.toString(); } }
  • 46. Dependency Inversion Principle (DIP) - Solution Solution: Use Interfaces Because the dependency of one class to another one should depend on the smallest possible interface.
  • 47. Dependency Inversion Principle (DIP) - Solution 1) BankAccount Interface Public Interface BankAccount{ public String currentBalance (); } 2) StubBankAccount class Class StubBankAccount implements BankAccount{ public String currentBalance (){ return “3000”; } }
  • 48. Dependency Inversion Principle (DIP) - Solution 3) Implementation of BankAccount class Class BankAccountImpl implements BankAccount { public String currentBalance (){ Your balance is: ” + ba.currentBalance(); } }
  • 49. Dependency Inversion Principle (DIP) - Solution 4) Class ATM{ private BankAccount ba; ATM(BankAccount ba){ this.ba = ba; } public String displayBalance(){ return “ Your balance is: ” + ba.currentBalance(); } }
  • 50. Dependency Inversion Principle (DIP) - Solution 5) Class ATMTest{ @Test public void shouldDisplayTheBalance(){ StubBankAccount sba = new StubBankAccount(); ATM atm = new ATM(sba); assertEquals( “ Your balance is: 3000”, atm.displaybalance()); } }
  • 51. Dependency Inversion Principle (DIP) - Solution 5) Class SomeClassUsingATM{ BankAccountImpl ba = new BankAccountImpl(); ATM atm = new ATM(ba); sopln (atm.displayBalance()); }
  • 52. Dependency Inversion Principle (DIP) • What Inversion means in DIP?? ▫ It is primarily about reversing the conventional direction of dependencies from "higher level" components to "lower level" components such that "lower level" components are dependent upon the interfaces owned by the "higher level" components.
  • 53. Dependency Inversion Principle (DIP) - Advantage • Choose which implementation is better suited for your particular environment • Either at compile time in the application, or • At the runtime by configuration. • Simplifies the unit testing. • Loosely coupled design.
  • 54. Inversion Of Control (IOC) • Inversion of Control is a design pattern where an Objects gets handed its dependency by an outside framework, rather than asking a framework for its dependency. • The benefits of IoC are: ▫ You have no dependency on a central framework, so this can be changed if desired. ▫ Since objects are created by injection, preferably using interfaces, it's easy to create unit tests that replace dependencies with mock versions. ▫ Decoupling off code.
  • 55. Inversion Of Control (IOC) • The "inversion" in DIP is not the same as in Inversion of Control. ▫ The first one is about compile-time dependencies, while the second one is about the flow of control between methods at runtime.
  • 56. Dependency Inversion Principle (DIP) • Any Questions on DIP???
  • 57. So, What is Dependency Inversion Principle (DIP)?
  • 58. Summary Principles of class design (aka SOLID): • Single Responsibility Principle (SRP) ▫ Create as many classes you want but  They should follow some real world entity  And have single responsibility • Open Closed Principle (OCP) ▫ Open for Extension, Closed for Modification
  • 59. Summary • Liskov Substitution Principle (LSP) ▫ Object of derived class can be passed instead of object of base class without changing the behavior of program. • Interface Segregation Principle (ISP) ▫ Create multiple client specific interface rather than creating single interface for multiple clients.
  • 60. Summary • Dependency Inversion Principle (DIP) ▫ It is the strategy of depending upon interfaces or abstract functions and classes, rather than upon concrete functions and classes
  • 61. Bibliography • http:// www.objectmentor.com/omSolutions/oops_what.htm • http://c2.com/cgi/wiki?PrinciplesOfObjectOrientedD