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

What's hot

Learning solid principles using c#
Learning solid principles using c#Learning solid principles using c#
Learning solid principles using c#
Aditya Kumar Rajan
 
SOLID
SOLIDSOLID
Single Responsibility Principle
Single Responsibility PrincipleSingle Responsibility Principle
Single Responsibility Principle
Eyal Golan
 
Solid principles
Solid principlesSolid principles
Solid principles
Declan Whelan
 
Gradle
GradleGradle
Solid design principles
Solid design principlesSolid design principles
Solid design principles
Mahmoud Asadi
 
SOLID Design Principles applied in Java
SOLID Design Principles applied in JavaSOLID Design Principles applied in Java
SOLID Design Principles applied in Java
Ionut Bilica
 
Clean code: SOLID
Clean code: SOLIDClean code: SOLID
Clean code: SOLID
Indeema Software Inc.
 
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
Ricardo Wilkins
 
OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ OO Design and Design Patterns in C++
OO Design and Design Patterns in C++
Ganesh Samarthyam
 
Introduction to Design Patterns and Singleton
Introduction to Design Patterns and SingletonIntroduction to Design Patterns and Singleton
Introduction to Design Patterns and Singleton
Jonathan Simon
 
Introduction to SOLID Principles
Introduction to SOLID PrinciplesIntroduction to SOLID Principles
Introduction to SOLID Principles
Ganesh Samarthyam
 
Advance oops concepts
Advance oops conceptsAdvance oops concepts
Advance oops concepts
Sangharsh agarwal
 
Four Pillers Of OOPS
Four Pillers Of OOPSFour Pillers Of OOPS
Four Pillers Of OOPS
Shwetark Deshpande
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module Patterns
Nicholas Jansma
 
Design Pattern For C# Part 1
Design Pattern For C# Part 1Design Pattern For C# Part 1
Design Pattern For C# Part 1
Shahzad
 
Strategy Pattern
Strategy PatternStrategy Pattern
Strategy PatternGuo Albert
 

What's hot (20)

Learning solid principles using c#
Learning solid principles using c#Learning solid principles using c#
Learning solid principles using c#
 
SOLID
SOLIDSOLID
SOLID
 
Single Responsibility Principle
Single Responsibility PrincipleSingle Responsibility Principle
Single Responsibility Principle
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
Solid principles
Solid principlesSolid principles
Solid principles
 
Gradle
GradleGradle
Gradle
 
Solid design principles
Solid design principlesSolid design principles
Solid design principles
 
SOLID Design Principles applied in Java
SOLID Design Principles applied in JavaSOLID Design Principles applied in Java
SOLID Design Principles applied in Java
 
Clean code: SOLID
Clean code: SOLIDClean code: SOLID
Clean code: SOLID
 
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
 
OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ OO Design and Design Patterns in C++
OO Design and Design Patterns in C++
 
Introduction to Design Patterns and Singleton
Introduction to Design Patterns and SingletonIntroduction to Design Patterns and Singleton
Introduction to Design Patterns and Singleton
 
Introduction to SOLID Principles
Introduction to SOLID PrinciplesIntroduction to SOLID Principles
Introduction to SOLID Principles
 
Advance oops concepts
Advance oops conceptsAdvance oops concepts
Advance oops concepts
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
Four Pillers Of OOPS
Four Pillers Of OOPSFour Pillers Of OOPS
Four Pillers Of OOPS
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module Patterns
 
Oops ppt
Oops pptOops ppt
Oops ppt
 
Design Pattern For C# Part 1
Design Pattern For C# Part 1Design Pattern For C# Part 1
Design Pattern For C# Part 1
 
Strategy Pattern
Strategy PatternStrategy Pattern
Strategy Pattern
 

Viewers also liked

OO design principles & heuristics
OO design principles & heuristicsOO design principles & heuristics
OO design principles & heuristics
Dhaval Shah
 
SOLID design principles applied in Java
SOLID design principles applied in JavaSOLID design principles applied in Java
SOLID design principles applied in Java
Bucharest Java User Group
 
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
 
SOLID mit Java 8
SOLID mit Java 8SOLID mit Java 8
SOLID mit Java 8
Roland Mast
 
Object-oriented design principles
Object-oriented design principlesObject-oriented design principles
Object-oriented design principles
Xiaoyan Chen
 
Design for Testability
Design for TestabilityDesign for Testability
Design for Testability
Stanislav Tiurikov
 
Implementing The Open/Closed Principle
Implementing The Open/Closed PrincipleImplementing The Open/Closed Principle
Implementing The Open/Closed PrincipleSam Hennessy
 
SOLID Principles and Design Patterns
SOLID Principles and Design PatternsSOLID Principles and Design Patterns
SOLID Principles and Design Patterns
Ganesh Samarthyam
 
Principles of object oriented programming
Principles of object oriented programmingPrinciples of object oriented programming
Principles of object oriented programming
Amogh Kalyanshetti
 
List of Software Development Model and Methods
List of Software Development Model and MethodsList of Software Development Model and Methods
List of Software Development Model and Methods
Riant Soft
 

Viewers also liked (10)

OO design principles & heuristics
OO design principles & heuristicsOO design principles & heuristics
OO design principles & heuristics
 
SOLID design principles applied in Java
SOLID design principles applied in JavaSOLID design principles applied in Java
SOLID design principles applied in Java
 
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
 
SOLID mit Java 8
SOLID mit Java 8SOLID mit Java 8
SOLID mit Java 8
 
Object-oriented design principles
Object-oriented design principlesObject-oriented design principles
Object-oriented design principles
 
Design for Testability
Design for TestabilityDesign for Testability
Design for Testability
 
Implementing The Open/Closed Principle
Implementing The Open/Closed PrincipleImplementing The Open/Closed Principle
Implementing The Open/Closed Principle
 
SOLID Principles and Design Patterns
SOLID Principles and Design PatternsSOLID Principles and Design Patterns
SOLID Principles and Design Patterns
 
Principles of object oriented programming
Principles of object oriented programmingPrinciples of object oriented programming
Principles of object oriented programming
 
List of Software Development Model and Methods
List of Software Development Model and MethodsList of Software Development Model and Methods
List of Software Development Model and Methods
 

Similar to principles of object oriented class design

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
Muhammad Raza
 
Object Oriented Concepts and Principles
Object Oriented Concepts and PrinciplesObject Oriented Concepts and Principles
Object Oriented Concepts and Principles
deonpmeyer
 
Object Oriented Principle’s
Object Oriented Principle’sObject Oriented Principle’s
Object Oriented Principle’s
vivek p s
 
L22 Design Principles
L22 Design PrinciplesL22 Design Principles
L22 Design Principles
Ólafur Andri Ragnarsson
 
L07 Design Principles
L07 Design PrinciplesL07 Design Principles
L07 Design Principles
Ólafur Andri Ragnarsson
 
"SOLID" Object Oriented Design Principles
"SOLID" Object Oriented Design Principles"SOLID" Object Oriented Design Principles
"SOLID" Object Oriented Design PrinciplesSerhiy Oplakanets
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
Yi-Huan Chan
 
An Introduction to the SOLID Principles
An Introduction to the SOLID PrinciplesAn Introduction to the SOLID Principles
An Introduction to the SOLID Principles
Attila Bertók
 
core_java.ppt
core_java.pptcore_java.ppt
core_java.ppt
YashikaDave
 
Software Design Principles (SOLID)
Software Design Principles (SOLID)Software Design Principles (SOLID)
Software Design Principles (SOLID)
ASIMYILDIZ
 
SOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principlesSOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principlesSergey Karpushin
 
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
 
NUS Hackers Club Mar 21 - Whats New in JavaSE 8?
NUS Hackers Club Mar 21 - Whats New in JavaSE 8?NUS Hackers Club Mar 21 - Whats New in JavaSE 8?
NUS Hackers Club Mar 21 - Whats New in JavaSE 8?
Chuk-Munn Lee
 
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Raffi Khatchadourian
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphism
mcollison
 
CLEAN CODING AND DEVOPS Final.pptx
CLEAN CODING AND DEVOPS Final.pptxCLEAN CODING AND DEVOPS Final.pptx
CLEAN CODING AND DEVOPS Final.pptx
JEEVANANTHAMG6
 
Pavlo Zhdanov "Mastering solid and base principles for software design"
Pavlo Zhdanov "Mastering solid and base principles for software design"Pavlo Zhdanov "Mastering solid and base principles for software design"
Pavlo Zhdanov "Mastering solid and base principles for software design"
LogeekNightUkraine
 
Solid principles - Object oriendte
Solid principles - Object oriendteSolid principles - Object oriendte
Solid principles - Object oriendte
inTwentyEight Minutes
 

Similar to principles of object oriented class design (20)

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
 
Object Oriented Concepts and Principles
Object Oriented Concepts and PrinciplesObject Oriented Concepts and Principles
Object Oriented Concepts and Principles
 
Object Oriented Principle’s
Object Oriented Principle’sObject Oriented Principle’s
Object Oriented Principle’s
 
L22 Design Principles
L22 Design PrinciplesL22 Design Principles
L22 Design Principles
 
L07 Design Principles
L07 Design PrinciplesL07 Design Principles
L07 Design Principles
 
"SOLID" Object Oriented Design Principles
"SOLID" Object Oriented Design Principles"SOLID" Object Oriented Design Principles
"SOLID" Object Oriented Design Principles
 
Oop principles
Oop principlesOop principles
Oop principles
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
SOLID
 SOLID SOLID
SOLID
 
An Introduction to the SOLID Principles
An Introduction to the SOLID PrinciplesAn Introduction to the SOLID Principles
An Introduction to the SOLID Principles
 
core_java.ppt
core_java.pptcore_java.ppt
core_java.ppt
 
Software Design Principles (SOLID)
Software Design Principles (SOLID)Software Design Principles (SOLID)
Software Design Principles (SOLID)
 
SOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principlesSOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principles
 
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#
 
NUS Hackers Club Mar 21 - Whats New in JavaSE 8?
NUS Hackers Club Mar 21 - Whats New in JavaSE 8?NUS Hackers Club Mar 21 - Whats New in JavaSE 8?
NUS Hackers Club Mar 21 - Whats New in JavaSE 8?
 
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphism
 
CLEAN CODING AND DEVOPS Final.pptx
CLEAN CODING AND DEVOPS Final.pptxCLEAN CODING AND DEVOPS Final.pptx
CLEAN CODING AND DEVOPS Final.pptx
 
Pavlo Zhdanov "Mastering solid and base principles for software design"
Pavlo Zhdanov "Mastering solid and base principles for software design"Pavlo Zhdanov "Mastering solid and base principles for software design"
Pavlo Zhdanov "Mastering solid and base principles for software design"
 
Solid principles - Object oriendte
Solid principles - Object oriendteSolid principles - Object oriendte
Solid principles - Object oriendte
 

Recently uploaded

Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 

Recently uploaded (20)

Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 

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