The OO Design Principles Steve Zhang
Introduction Software design definition Software nature - entropy Discuss Symptoms of poor software design Discuss 5 OO software design principles Law of Demeter Don’t Repeat yourself principle Design By Contract
The presentation comes from two books Author: Robert  C.  Martin Nick Name: Uncle Bob Agile Software Development, principles, patterns and practices
The pragmatic Programmer – from journeyman to master Andy Hunt Dave Thomas
What is Software Design? The source code is the design UML diagram represents part of a design, but  it is not the design. Because the design can only be verified through source code The software design process includes coding, testing, refactoring…  The programmer is real software designer
Software nature – Software entropy Software tends to degrade / decay Software rot – like a piece of bad meat
The cost of change curve
Developers productivity vs. time Question: does our project manager consider this curve when doing estimations?
Design Smells – The Odors of Rotting Software Rigidity – The design is hard to change  Fragility – The design is easy to break  Immobility – The design is hard to reuse  Viscosity –  It is hard to do the right thing  Needless complexity – Overdesign  Needless Repetition – Mouse abuse  Opacity – Disorganized expression
Rigidity  The tendency for software to be difficult to change Single change causes cascade of subsequent changes in dependent modules  The more modules must be changed, the more rigid the design
Fragility  The tendency for a program to break in many places when a single changes is made The new problems in area that have no conceptual relationship with the area that was changed As the fragility of a module increases, the likelihood that a change will introduce unexpected problems approaches certainty.
Immobility Difficult to reuse A design is immobile when it contains parts that could be useful in other systems, but the effort and risk involved with separating those parts from the original system are too great.  This is an unfortunate but very common occurrence.
Viscosity  It is easy to do the wrong thing, but hard to do the right thing. When the design-preserving methods are more difficult to use than the hacks, the viscosity of the design is high  When development environment is slow and inefficient, developers will be tempted to do wrong things
Needless complexity Overdesign A design smells of needless complexity when it contains elements that aren't currently useful  The design becomes littered with constructs that are never used  Makes the software complex and difficult to understand.
Needless Repetition The design contains repeating structures that could be unified under a single abstraction The problem is due to developer’s abuse of cut and paste. It is really hard to maintain and understand the system with duplicated code. Duplication is Evil! DRY – DON’T REPEAT YOURSELF
Opacity Opacity is the tendency of a module to be difficult to read and understand  The code does not express its intent well The code is written in an opaque and convoluted manner
What Stimulates the Software to Rot? Requirements keep change –  design degradation People change – violate the original design Tight schedule pressure Traditional waterfall process can not prevent software from rotting Lack of Feedback Lack of Communication
The psychology reason – Broken Window Theory  Came from city crime researcher A broken window will trigger a building into a smashed and abandoned derelict So does the software Don’t live with the Broken window From the book Pragmatic Programmer – From Journeyman to Master
How can we prevent software from rotting? Applies OO design principles Bad design usually violates design principles Uses design patterns Follows agile practices Refactoring will reduce the software entropy
 
 
S.O.L.I.D Design Principles SRP – The Single Responsibility Principle OCP – The Open-Closed Principle LSP – The Liskov Substitution Principle ISP – The Interface Segregation Principle DIP – The Dependency Inversion Principle
SRP: The Single-Responsibility Principle A class should have only one reason to change. If a class has more than one responsibility, then the responsibilities becomes coupled. SRP is one of the simplest of the principles, and the one of the hardest to get right.
OCP: The Open-Closed Principle Software entities( classes, modules, functions, etc.) should be open for extension, but closed for modification  “Open for extension” The behavior of the module can be extended “Closed for modification” Extending the behavior of a module does not resulting changes to the source code or binary code of the module.
OCP – Abstraction is the key Example: Strategy pattern Client is both open and closed
OCP Summary The Open/Closed Principle is at the heart of object-oriented design  Conformance to OCP is what yields the greatest benefits claimed for object-oriented technology: flexibility, reusability, and maintainability.
Further thinking of OCP Does J2ME preprocess violate OCP or not? My answer: Yes preprocess itself is anti-OO, give the developer a backdoor to violate OO brutally Every time we add a new feature, we have to modify the existing source code It is difficult to refactor Difficult to reuse, maintain and understand So we should be very careful to use preprocess, use it as the last choice instead of the first choice > 90% our preprocess code can be removed!
LSP: Liskov Substitution Principle Subtypes must be substitutable for their base types. LSP defines the OO inheritance principle. If a client uses a base class, then it should not differentiate the base class from derived class, which means the derived class can substitute the base class
LSP violation example: A violation of LSP causing a violation of OCP public enum ShapeType {square, circle}; public class Shape{  public static void DrawShape(Shape s)  {  if(s.type == ShapeType.square)  (s as Square).Draw();  else if(s.type == ShapeType.circle)  (s as Circle).Draw();  } } public class Circle : Shape {  public void Draw() {/* draws the circle */} } public class Square : Shape{  public void Draw() {/* draws the square */} }   Violate OCP Not  substitutable
Another LSP violation example: Rectangle and Square void g(Rectangle r)  {  r.setWidth(5);  r.setHeight(4);  if(r.getArea() != 20)  throw new Exception("Bad area!"); }  Square’s behavior is changed, so it is not substitutable to Rectangle IS-A Relationship Square is not Rectangle!
LSP is closely related to Design By Contract methodology A routine re-declaration [in a derivative] may only replace the original precondition by one equal or weaker, and the original post-condition by one equal or stronger. Derived classes must accept anything that the base class could accept  derived classes must conform to all the post-conditions of the base
DIP: The Dependency Inversion Principle High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details. Details should depend on abstractions. DIP is at the very heart of framework design.
A DIP example DIP violation DIP
DIP: an inversion of ownership Inversion is not just one of dependencies, also one of interface ownership. Clients own the abstraction interfaces. Hollywood principle: “Don’t call us, we’ll call you”.
DIP: Depend on Abstractions No variable should hold a reference to a concrete class. No class should derive from a concrete class. No method should override an implemented method of any of its base classes.
DIP is also regarded as Dependency Injection & Inversion of Control  Dependency injection is the core of the famous Spring framework.
DIP Summary Inversion of dependencies is the hallmark of good object-oriented design. If its dependencies are inverted, it has an OO design; if its dependencies are not inverted, it has a procedural design.  DIP makes abstractions and details isolated from each other, the code is much easier to maintain.
ISP: The Interface Segregation Principle  Clients should not be forced to depend on methods they do not use.   ISP deals with designing cohesive interfaces and avoiding "fat" interfaces. The dependency of one class to another one should depend on the smallest possible interface.  The interfaces of the class can be broken up into groups of methods. Each group serves a different set of clients.
An violation of ISP example ISP violation
An ISP Violation example: solution Segregated interface
LoD - Law of Demeter Principle of Least Knowledge Only talk to your immediate friends Don’t talk to strangers Write “shy” codes Minimize coupling
LoD formal definition A method M of an object O may only invoke the methods of the following kinds of objects O itself  M's parameters  any objects created/instantiated within M  O's direct component objects
LoD
LoD violation example final String outputDir = ctxt.getOptions().getScratchDir().getAbsolutePath(); a.getB().getC().doSomething() - Transitive Navigation From book Clean Code – A handbook of Agile Software Craftsmanship  ( Robert C. Martin)
DRY – Don’t Repeat Yourself Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.  Following DRY will make software developments easier to understand and maintain Duplication is Evil Originated from the book –  The pragmatic programmer
How can we prevent duplication? Code duplication – Refactoring code, make it easier to reuse Defect duplication – communication, code review, internal forum, internal wiki, and document. System design duplication (spec, configuration, deployment, database schema) – keep improving the system design Build duplication – build automation Use meta programming and code generator technology. Duplication is a waste in software development, we need to eliminate the waste
DBC - Design By Contract A contract defines rights and responsibilities between method caller and a routine Preconditions – the routine’s requirements, it is the caller’s responsibility to pass the good data Postconditions – What the routine is guaranteed to do Class invariants – A class ensures that this condition is always true from perspective of a caller
Design By Contract Definition The contract between a routine and any potential caller can thus be read as   If all the routine’s preconditions are met by the caller, the routine shall guarantee that all posconditions and invariants will be true when it completes.
DBC DBC concept is developed by Betrand Meyer for the language Eiffel. We can use assertive programming to implement DBC assert(string != null); We also use the DBC concept in JUnit test. DBC give us a good concept to write a robust software, even java does not support it.
Summary The OO design principles help us: As guidelines when designing flexible, maintainable and reusable software As standards when identifying the bad design As laws to argue when doing code review
References Book - Agile Software Development, Principles, Patterns, and Practices, Robert C. Martin Book - Agile Principles, Patterns, and Practices in C# (Robert C. Martin Series)  Book- The Pragmatic Programmer, Article- What is software design?  http://www.bleading-edge.com/Publications/C++Journal/Cpjour2.htm Resources from Object Mentor website:  http://objectmentor.com/resources/omi_reports_index.html http://mmiika.wordpress.com/oo-design-principles/
Your feedback is very important!
Thank You!

The OO Design Principles

  • 1.
    The OO DesignPrinciples Steve Zhang
  • 2.
    Introduction Software designdefinition Software nature - entropy Discuss Symptoms of poor software design Discuss 5 OO software design principles Law of Demeter Don’t Repeat yourself principle Design By Contract
  • 3.
    The presentation comesfrom two books Author: Robert C. Martin Nick Name: Uncle Bob Agile Software Development, principles, patterns and practices
  • 4.
    The pragmatic Programmer– from journeyman to master Andy Hunt Dave Thomas
  • 5.
    What is SoftwareDesign? The source code is the design UML diagram represents part of a design, but it is not the design. Because the design can only be verified through source code The software design process includes coding, testing, refactoring… The programmer is real software designer
  • 6.
    Software nature –Software entropy Software tends to degrade / decay Software rot – like a piece of bad meat
  • 7.
    The cost ofchange curve
  • 8.
    Developers productivity vs.time Question: does our project manager consider this curve when doing estimations?
  • 9.
    Design Smells –The Odors of Rotting Software Rigidity – The design is hard to change Fragility – The design is easy to break Immobility – The design is hard to reuse Viscosity – It is hard to do the right thing Needless complexity – Overdesign Needless Repetition – Mouse abuse Opacity – Disorganized expression
  • 10.
    Rigidity Thetendency for software to be difficult to change Single change causes cascade of subsequent changes in dependent modules The more modules must be changed, the more rigid the design
  • 11.
    Fragility Thetendency for a program to break in many places when a single changes is made The new problems in area that have no conceptual relationship with the area that was changed As the fragility of a module increases, the likelihood that a change will introduce unexpected problems approaches certainty.
  • 12.
    Immobility Difficult toreuse A design is immobile when it contains parts that could be useful in other systems, but the effort and risk involved with separating those parts from the original system are too great. This is an unfortunate but very common occurrence.
  • 13.
    Viscosity Itis easy to do the wrong thing, but hard to do the right thing. When the design-preserving methods are more difficult to use than the hacks, the viscosity of the design is high When development environment is slow and inefficient, developers will be tempted to do wrong things
  • 14.
    Needless complexity OverdesignA design smells of needless complexity when it contains elements that aren't currently useful The design becomes littered with constructs that are never used Makes the software complex and difficult to understand.
  • 15.
    Needless Repetition Thedesign contains repeating structures that could be unified under a single abstraction The problem is due to developer’s abuse of cut and paste. It is really hard to maintain and understand the system with duplicated code. Duplication is Evil! DRY – DON’T REPEAT YOURSELF
  • 16.
    Opacity Opacity isthe tendency of a module to be difficult to read and understand The code does not express its intent well The code is written in an opaque and convoluted manner
  • 17.
    What Stimulates theSoftware to Rot? Requirements keep change – design degradation People change – violate the original design Tight schedule pressure Traditional waterfall process can not prevent software from rotting Lack of Feedback Lack of Communication
  • 18.
    The psychology reason– Broken Window Theory Came from city crime researcher A broken window will trigger a building into a smashed and abandoned derelict So does the software Don’t live with the Broken window From the book Pragmatic Programmer – From Journeyman to Master
  • 19.
    How can weprevent software from rotting? Applies OO design principles Bad design usually violates design principles Uses design patterns Follows agile practices Refactoring will reduce the software entropy
  • 20.
  • 21.
  • 22.
    S.O.L.I.D Design PrinciplesSRP – The Single Responsibility Principle OCP – The Open-Closed Principle LSP – The Liskov Substitution Principle ISP – The Interface Segregation Principle DIP – The Dependency Inversion Principle
  • 23.
    SRP: The Single-ResponsibilityPrinciple A class should have only one reason to change. If a class has more than one responsibility, then the responsibilities becomes coupled. SRP is one of the simplest of the principles, and the one of the hardest to get right.
  • 24.
    OCP: The Open-ClosedPrinciple Software entities( classes, modules, functions, etc.) should be open for extension, but closed for modification “Open for extension” The behavior of the module can be extended “Closed for modification” Extending the behavior of a module does not resulting changes to the source code or binary code of the module.
  • 25.
    OCP – Abstractionis the key Example: Strategy pattern Client is both open and closed
  • 26.
    OCP Summary TheOpen/Closed Principle is at the heart of object-oriented design Conformance to OCP is what yields the greatest benefits claimed for object-oriented technology: flexibility, reusability, and maintainability.
  • 27.
    Further thinking ofOCP Does J2ME preprocess violate OCP or not? My answer: Yes preprocess itself is anti-OO, give the developer a backdoor to violate OO brutally Every time we add a new feature, we have to modify the existing source code It is difficult to refactor Difficult to reuse, maintain and understand So we should be very careful to use preprocess, use it as the last choice instead of the first choice > 90% our preprocess code can be removed!
  • 28.
    LSP: Liskov SubstitutionPrinciple Subtypes must be substitutable for their base types. LSP defines the OO inheritance principle. If a client uses a base class, then it should not differentiate the base class from derived class, which means the derived class can substitute the base class
  • 29.
    LSP violation example:A violation of LSP causing a violation of OCP public enum ShapeType {square, circle}; public class Shape{ public static void DrawShape(Shape s) { if(s.type == ShapeType.square) (s as Square).Draw(); else if(s.type == ShapeType.circle) (s as Circle).Draw(); } } public class Circle : Shape { public void Draw() {/* draws the circle */} } public class Square : Shape{ public void Draw() {/* draws the square */} } Violate OCP Not substitutable
  • 30.
    Another LSP violationexample: Rectangle and Square void g(Rectangle r) { r.setWidth(5); r.setHeight(4); if(r.getArea() != 20) throw new Exception("Bad area!"); } Square’s behavior is changed, so it is not substitutable to Rectangle IS-A Relationship Square is not Rectangle!
  • 31.
    LSP is closelyrelated to Design By Contract methodology A routine re-declaration [in a derivative] may only replace the original precondition by one equal or weaker, and the original post-condition by one equal or stronger. Derived classes must accept anything that the base class could accept derived classes must conform to all the post-conditions of the base
  • 32.
    DIP: The DependencyInversion Principle High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details. Details should depend on abstractions. DIP is at the very heart of framework design.
  • 33.
    A DIP exampleDIP violation DIP
  • 34.
    DIP: an inversionof ownership Inversion is not just one of dependencies, also one of interface ownership. Clients own the abstraction interfaces. Hollywood principle: “Don’t call us, we’ll call you”.
  • 35.
    DIP: Depend onAbstractions No variable should hold a reference to a concrete class. No class should derive from a concrete class. No method should override an implemented method of any of its base classes.
  • 36.
    DIP is alsoregarded as Dependency Injection & Inversion of Control Dependency injection is the core of the famous Spring framework.
  • 37.
    DIP Summary Inversionof dependencies is the hallmark of good object-oriented design. If its dependencies are inverted, it has an OO design; if its dependencies are not inverted, it has a procedural design. DIP makes abstractions and details isolated from each other, the code is much easier to maintain.
  • 38.
    ISP: The InterfaceSegregation Principle Clients should not be forced to depend on methods they do not use. ISP deals with designing cohesive interfaces and avoiding "fat" interfaces. The dependency of one class to another one should depend on the smallest possible interface. The interfaces of the class can be broken up into groups of methods. Each group serves a different set of clients.
  • 39.
    An violation ofISP example ISP violation
  • 40.
    An ISP Violationexample: solution Segregated interface
  • 41.
    LoD - Lawof Demeter Principle of Least Knowledge Only talk to your immediate friends Don’t talk to strangers Write “shy” codes Minimize coupling
  • 42.
    LoD formal definitionA method M of an object O may only invoke the methods of the following kinds of objects O itself M's parameters any objects created/instantiated within M O's direct component objects
  • 43.
  • 44.
    LoD violation examplefinal String outputDir = ctxt.getOptions().getScratchDir().getAbsolutePath(); a.getB().getC().doSomething() - Transitive Navigation From book Clean Code – A handbook of Agile Software Craftsmanship ( Robert C. Martin)
  • 45.
    DRY – Don’tRepeat Yourself Every piece of knowledge must have a single, unambiguous, authoritative representation within a system. Following DRY will make software developments easier to understand and maintain Duplication is Evil Originated from the book – The pragmatic programmer
  • 46.
    How can weprevent duplication? Code duplication – Refactoring code, make it easier to reuse Defect duplication – communication, code review, internal forum, internal wiki, and document. System design duplication (spec, configuration, deployment, database schema) – keep improving the system design Build duplication – build automation Use meta programming and code generator technology. Duplication is a waste in software development, we need to eliminate the waste
  • 47.
    DBC - DesignBy Contract A contract defines rights and responsibilities between method caller and a routine Preconditions – the routine’s requirements, it is the caller’s responsibility to pass the good data Postconditions – What the routine is guaranteed to do Class invariants – A class ensures that this condition is always true from perspective of a caller
  • 48.
    Design By ContractDefinition The contract between a routine and any potential caller can thus be read as If all the routine’s preconditions are met by the caller, the routine shall guarantee that all posconditions and invariants will be true when it completes.
  • 49.
    DBC DBC conceptis developed by Betrand Meyer for the language Eiffel. We can use assertive programming to implement DBC assert(string != null); We also use the DBC concept in JUnit test. DBC give us a good concept to write a robust software, even java does not support it.
  • 50.
    Summary The OOdesign principles help us: As guidelines when designing flexible, maintainable and reusable software As standards when identifying the bad design As laws to argue when doing code review
  • 51.
    References Book -Agile Software Development, Principles, Patterns, and Practices, Robert C. Martin Book - Agile Principles, Patterns, and Practices in C# (Robert C. Martin Series) Book- The Pragmatic Programmer, Article- What is software design? http://www.bleading-edge.com/Publications/C++Journal/Cpjour2.htm Resources from Object Mentor website: http://objectmentor.com/resources/omi_reports_index.html http://mmiika.wordpress.com/oo-design-principles/
  • 52.
    Your feedback isvery important!
  • 53.