principles of object oriented class design


Published on

principles of object oriented class design, SOLID principle

Published in: Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

principles of object oriented class design

  2. 2. AgendaPrinciples 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. 3. What do you mean by a good classdesign??
  4. 4. Good class design• Represents any real world entity• Better code readability/ understanding• Loosely coupled with other classes• Compact & Optimized• Easily testable
  5. 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. 6. Single Responsibility Principle (SRP) - ExampleClass 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. 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. 8. Single Responsibility Principle (SRP) - SolutionClass 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. 9. Single Responsibility Principle (SRP) - SolutionClass 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. 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. 11. Single Responsibility Principle (SRP)• Any Questions on SRP???
  12. 12. So, What is Single Responsibility Principle (SRP)?
  13. 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. 14. Open Closed Principle (OCP) - ExamplePolymorphism 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) // on}
  15. 15. Open Closed Principle (OCP) - Example Consider the class design something like this: Here LogOn has been closed for modification.
  16. 16. Open Closed Principle (OCP) - ExampleAbstract 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. 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. 18. Open Closed Principle (OCP)Any questions??
  19. 19. So, What is Open Closed Principle (OCP)??
  20. 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. 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. 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. 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. 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. 25. Liskov Substitution Principle (LSP)Consider the following function:void func(Rectangle r){ r.SetLength(20); r.SetBreadth(32);}
  26. 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. 27. Liskov Substitution Principle (LSP) Thus, violations of LSP are latent violations of OCP.
  28. 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. 29. Liskov Substitution Principle (LSP)• Any Questions on LSP???
  30. 30. So, What is Liskov Substitution Principle (LSP)??
  31. 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 dont use. ▫ Instead of one fat interface many small interfaces are preferred based on groups of methods, each one serving one sub-module.
  32. 32. Interface Segregation Principle (ISP)The methods needed by each client are placed in single interface that arespecific to the client. Fat Service with Integrated Interfaces
  33. 33. Interface Segregation Principle (ISP)The methods needed by each client are placed in special interfaces that arespecific to that client. Segregated Interfaces
  34. 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. 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 dont eat so they dont 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 dont have to implement it because they dont eat.
  36. 36. Interface Segregation Principle (ISP) - Example// interface segregation principle - bad exampleinterface IWorker { public void work(); public void eat();}class Worker implements IWorker{ public void work() { // ....working } public void eat() { // ...... eating in lunch break }}
  37. 37. Interface Segregation Principle (ISP) - Exampleclass 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() {; }}
  38. 38. Interface Segregation Principle (ISP) - Solution// interface segregation principle - good exampleinterface IWorkable { public void work();}interface IEatable{ public void eat();}
  39. 39. Interface Segregation Principle (ISP) - Solutionclass 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. 40. Interface Segregation Principle (ISP) - Solutionclass Robot implements IWorkable { public void work() { //.... working}}class Manager { IWorkable worker; public void setWorker(IWorkable w) { worker=w; } public void manage() {; }}
  41. 41. Interface Segregation Principle (ISP)Any Questions??
  42. 42. So, What is Interface Segregation Principle (ISP)?
  43. 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. 44. Dependency Inversion Principle (DIP) - ExampleExample: ATM & Bank AccountClass ATM{ private BankAccount ba = new BankAccount(); public String displayBalance(){ return “ Your balance is: ” + ba.currentBalance(); }}
  45. 45. Dependency Inversion Principle (DIP) - ExampleClass BankAccount{ private Double bal; //setters & getters public String currentBalance (){ return bal.toString(); }}
  46. 46. Dependency Inversion Principle (DIP) - SolutionSolution: Use Interfaces Because the dependency of one class to another one should depend on the smallest possible interface.
  47. 47. Dependency Inversion Principle (DIP) - Solution1) BankAccount InterfacePublic Interface BankAccount{ public String currentBalance ();}2) StubBankAccount classClass StubBankAccount implements BankAccount{ public String currentBalance (){ return “3000”; }}
  48. 48. Dependency Inversion Principle (DIP) - Solution3) Implementation of BankAccount classClass BankAccountImpl implements BankAccount{ public String currentBalance (){ Your balance is: ” + ba.currentBalance(); }}
  49. 49. Dependency Inversion Principle (DIP) - Solution4) Class ATM{ private BankAccount ba; ATM(BankAccount ba){ = ba; } public String displayBalance(){ return “ Your balance is: ” + ba.currentBalance(); }}
  50. 50. Dependency Inversion Principle (DIP) - Solution5) Class ATMTest{ @Test public void shouldDisplayTheBalance(){ StubBankAccount sba = new StubBankAccount(); ATM atm = new ATM(sba); assertEquals( “ Your balance is: 3000”, atm.displaybalance()); }}
  51. 51. Dependency Inversion Principle (DIP) - Solution5) Class SomeClassUsingATM{ BankAccountImpl ba = new BankAccountImpl(); ATM atm = new ATM(ba); sopln (atm.displayBalance());}
  52. 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. 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. 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, its easy to create unit tests that replace dependencies with mock versions. ▫ Decoupling off code.
  55. 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. 56. Dependency Inversion Principle (DIP)• Any Questions on DIP???
  57. 57. So, What is Dependency Inversion Principle (DIP)?
  58. 58. SummaryPrinciples 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. 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. 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. 61. Bibliography• http://•
  62. 62. Questions??
  63. 63. Thank You