SOLID Software Design    @jankeesvanandel     @jwalgemoed        @JPoint       SOLID Software Design   1
About usJarno Walgemoed                 Jan-Kees van Andel–Architect @JPoint              –Architect @JPoint–Fa-Med       ...
Agenda – Goals – Code quality – SOLID – Other principles – Demo – Conclusion – Q&A                      SOLID Software Des...
Agenda – Goals – Code quality – SOLID – Other principles – Demo – Conclusion – Q&A                      SOLID Software Des...
GoalsNOT our goal               SOLID Software Design   5
GoalsMastery takes lots of practice  – You can’t learn to surf by reading a book  – Neither programming                   ...
Goals  “The 10.000 hour rule” – Malcolm Gladwell                  SOLID Software Design       7
Goals• ShuHaRi  – Shu: Traditional wisdom  – Ha: Breaking with tradition  – Ri: Transcendence                     SOLID So...
GoalsAfter this session  – you will NOT suddenly write better codeBut…  – you hopefully have some hooks to get better     ...
Agenda – Goals – Code quality – SOLID – Other principles – Demo – Conclusion – Q&A                      SOLID Software Des...
Code qualityIs this code quality?private   static   final   String   OID = "oId";private   static   final   String   TIME_...
Code qualityIs this code quality?@Controllerpublic class StartController {   @Autowired   public StartController(SessionDa...
Code qualityIs this code quality?                        SOLID Software Design   13
Code qualityIs this code quality?                        SOLID Software Design   14
Code qualityIs this code quality?/** * This controller contains default Action and Render mappings, * used as fallback for...
Code qualityIs this code quality?/** * This controller contains default Action and Render mappings, * used as fallback for...
Code qualityTonight, code quality means OO Design  – OOD is not free or easy, not even with Java/C#  – A lot of structured...
Code qualityTonight, code quality means SOLID principles  – Not about Object Oriented Modeling     • (Person, User, Plane ...
Code qualityTonight, code quality means Dependency Mgt  – Because     •   We DON’T want rigid code     •   We DON’T want c...
Code qualityWhy dependency Management?  – Because we don’t want code rot                    SOLID Software Design   20
Code qualityWhy dependency Management?  – Refactor sprint                      SOLID Software Design   21
Code qualityWhy dependency Management?  – Continuous refactoring                     SOLID Software Design   22
Agenda – Goals – Code quality – SOLID – Other principles – Demo – Conclusion – Q&A                      SOLID Software Des...
SOLIDSOLID  – First stated by Robert C. Martin in 1995     – “The Ten Commandments of OO Programming”                     ...
SOLIDSOLID:  – Later documented in “Agile Software    Development: Principles, Patterns and Practices”                    ...
SOLIDShort for:  – SRP: Single Responsibility Principle  – OCP: Open-Closed Principle  – LSP: Liskov Substitution Principl...
Single Responsibility Principle“A class should have only one reason to change”  – Theory  – Simple example  – Real world e...
Single Responsibility PrincipleTheory  – A Class Should Only Have One Reason To Change  – Also referred to with the term C...
Single Responsibility Principle                  SOLID Software Design   29
Single Responsibility PrincipleSimple example    – Database application interface specificationpublic interface Database {...
Single Responsibility PrincipleSimple example  – What if the protocol changes?  – What if the connection management change...
Single Responsibility PrincipleSimple example    – How about this?public interface DatabaseConnection {    public ResultSe...
Single Responsibility PrincipleSimple example  – DatabaseConnection implementations handle    querying  – DatabaseConnecti...
Single Responsibility PrincipleConsiderations  – Should we split every class we create? No.  – Will we end up with one-met...
Single Responsibility PrincipleConsiderations  – If the application doesn’t require changing either    of the coupled resp...
Single Responsibility PrincipleConclusion  – Simplest SOLID principle, hardest to get right  – Be critical deciding whethe...
Single Responsibility PrincipleQuestion: Real world usages of SRP?  – Examples in Java API  – Examples in GoF Design Patte...
Open-Closed Principle“Software entities should be open for extension,but closed for modification”  – Theory  – Simple exam...
Open-Closed PrincipleTheory  – Helps preventing rigidity and cascading changes  – Open for extension     • Behaviour of a ...
Open-Closed Principle                SOLID Software Design   40
Open-Closed PrincipleSimple Example    – We are using this Rectangle objectpublic class Rectangle {    private int width; ...
Open-Closed PrincipleSimple Example    – With this function we calculate area totalspublic class AreaCalculator {    publi...
Open-Closed PrincipleSimple Example    – Now we want to add a circle to the equationpublic class Circle {    private int r...
Open-Closed PrincipleSimple Example    – What happens to the calculation?public double calculateTotalArea(Object [] object...
Open-Closed PrincipleSimple Example  – This is poor design (of course)  – The calculate method is not closed for    modifi...
Open-Closed PrincipleSimple Example   – Introducing Shape and extending itpublic abstract class Shape {    public abstract...
Open-Closed PrincipleSimple Example    – Simplifies AreaCalculator substantially    – Allows future extensionpublic class ...
Open-Closed PrincipleSimple Example  – The calculation is now Open for extension and    closed for modification  – Adding ...
Open-Closed PrincipleConsiderations                 SOLID Software Design   49
Open-Closed PrincipleConsiderations  – Abstraction is key  – So… should we just abstract everything? No.  – Abstract eleme...
Open-Closed PrincipleConclusion  – At the heart of Object Oriented design  – Design using logical, useful abstractions  – ...
Open-Closed PrincipleQuestion: Real world usages of OCP?  – Examples in Java API  – Examples in GoF Design Patterns  – Big...
Liskov Substitution Principle“If for each object o1 of type S there is an object o2 oftype T such that for all programs P ...
Liskov Substitution Principle“Subtypes must be substitutable for their basetypes”  – Theory  – Simple example  – Real worl...
Liskov Substitution PrincipleTheory  – Polymorphism problem  – A extends B     • This means A IS-A B     • …but is this al...
Liskov Substitution Principle                 SOLID Software Design   56
Liskov Substitution PrincipleSimple Example  – Square extends Rectangle    • Square IS-A Rectangle, right?  – Difference b...
Liskov Substitution PrincipleSimple Example    – So, this is correct then?class Rectangle {    private int width;   privat...
Liskov Substitution PrincipleSimple Example   – Suppose we test the Square like thisSquare square = new Square(42);assertE...
Liskov Substitution PrincipleSimple Example    – Fixing is easy, but is this really the way to go?class Square extends Rec...
Liskov Substitution PrincipleSimple Example    – Maybe better to do thisclass Square extends Shape { // Immutable    priva...
Liskov Substitution PrincipleConsiderations  – The IS-A relationship not always applies in code     • A square is a rectan...
Liskov Substitution PrincipleConclusion  – Rule of thumb     • Instead of: A IS-A B, use: A is substitutable by B  – Inher...
Liskov Substitution PrincipleQuestion: Real world usages of LSP?  – Examples in Java API  – Examples in GoF Design Pattern...
Interface Segregation Principle“Clients should not be forced to depend onmethods that they do not use”  – Theory  – Simple...
Interface Segregation Principle                 SOLID Software Design   66
Interface Segregation PrincipleSimple Example   – Interface definition for a worker doing workpublic interface Worker {   ...
Interface Segregation PrincipleSimple Example   – Robots are also part of the businesspublic class Robot implements Worker...
Interface Segregation PrincipleSimple Example   – Split up the interfaces into sensible piecespublic interface NutritionCo...
Interface Segregation PrincipleSimple Example   – Implement the interfaces as neededpublic class Employee implements Worke...
Interface Segregation PrincipleSimple Example   – Class dealing with Worker objectspublic class WorkloadManager {    publi...
Interface Segregation PrincipleConsiderations  – Avoid coupling between interfaces and clients  – Clients should only depe...
Interface Segregation PrincipleConclusion  – Separate interfaces when it makes sense  – Don’t overdo it!     • Prevent cla...
Interface Segregation PrincipleQuestion: Real world usages of ISP?  – Examples in Java API  – Examples in GoF Design Patte...
Dependency Inversion Principle“High-level modules should not depend on low-level modules directly, but through abstraction...
Dependency Inversion Principle                SOLID Software Design   76
Dependency Inversion PrincipleSimple Example    – Application that monitors system statuspublic class SystemStatus {    pr...
Dependency Inversion PrincipleSimple Example   – HeatGauge implementationpublic class HeatGauge {    public int actualTemp...
Dependency Inversion PrincipleSimple Example    – Systemstatus directly depends on HeatGauge    – Changes to HeatGauge can...
Dependency Inversion PrincipleSimple Example   – Abstract away the dependencypublic interface HeatGauge {    public int ac...
Dependency Inversion PrincipleSimple Example    – Use the new abstractionpublic class SystemStatus {    // Less dependent ...
Dependency Inversion PrincipleSimple Example    – Improving the examplepublic class SystemStatus {    private HeatGauge he...
Dependency Inversion PrincipleConsiderations  – Clients should ‘own’ the interfaces used to access    low-level modules  –...
Dependency Inversion PrincipleConclusion  – Maybe the most relevant of all SOLID principles  – Allows robust code to be wr...
Dependency Inversion PrincipleQuestion: Real world usages of DIP?  – Examples in Java API  – Examples in GoF Design Patter...
Agenda – Goals – Code quality – SOLID – Other principles – Demo – Conclusion – Q&A                      SOLID Software Des...
Other principlesNot SOLID, but just as important!  – REP: Release reuse Equivalency Principle  – CCD: Common Closure Princ...
Other principlesNot SOLID, but just as important!  – REP: Release reuse Equivalency Principle  – CCD: Common Closure Princ...
Other principlesNot SOLID, but just as important!  – ADP: Acyclic Dependencies Principle  – SDP: Stable Dependencies Princ...
Agenda – Goals – Code quality – SOLID – Other principles – Demo – Conclusion – Q&A                      SOLID Software Des...
ConclusionDemo  – Small web application to demo the ideas                     SOLID Software Design    91
Agenda – Goals – Code quality – SOLID – Other principles – Demo – Conclusion – Q&A                      SOLID Software Des...
ConclusionMaster the SOLID principles  – Use it in your communications  – Use it to challenge your design/yourself  – Appl...
ConclusionSOLID principles are no hard rules  – Definitely no hard rules!  – Also no goals, just a means to an end  – Ther...
ConclusionDon’t be dogmatic  – Even Uncle Bob said this  – http://blog.objectmentor.com/articles/2009/02/06/on  – In respo...
Q&AAny questions left?                      SOLID Software Design   96
Upcoming SlideShare
Loading in …5
×

bGenius kennissessie_20120510

536 views

Published on

SOLID Software Design by jPoint.

Published in: Technology, Business
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
536
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
22
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide
  • Java API: -Examples: -Abusers: Almost every class with Context or Manager in it (javax.faces.FacesContext, javax.persistence.EntityManager, javax.servlet, HttpServletRequest, java.lang.Math, java.util.Collections) GoF Examples: Template Method, Chain of Responsibility, Decorator Abusers:
  • Java API: -Examples: javax.servlet.Filter, -Abusers: java.lang.String GoF -Examples: Template Method, Chain of Responsibility, Decorator, Abstract Factory, Command -Abusers: Singleton What about Aspect Oriented Programming? Open-Closed Principle on module level
  • Java API: -Examples: java.util.Collection, java.util.Set, java.util.List, java.util.Map, -Abusers: GoF -Examples: State, Strategy, Command, -Abusers: Template Method, Decorator
  • Java API: -Examples: Serializable, Cloneable, Collection (specifics are in List, Set, Map) -Abusers: Iterable (why .remove()?) GoF -Examples: Adapter, Mediator -Abusers:
  • Java API: -Examples: javax.servlet.HttpServlet (interfaces of HttpServletRequest/Response passed in, details are hidden) -Abusers: All static functions GoF -Examples: Strategy, State, Iterator, -Abusers: Spring Framework (Dependency Injection vs. Dependency Inversion)
  • bGenius kennissessie_20120510

    1. 1. SOLID Software Design @jankeesvanandel @jwalgemoed @JPoint SOLID Software Design 1
    2. 2. About usJarno Walgemoed Jan-Kees van Andel–Architect @JPoint –Architect @JPoint–Fa-Med r –Rabobank r pe pe–Blinker –SNS Bank lo ve–DJI elo D e –Apache MyFaces v –Devoxx Steering De SOLID Software Design 2
    3. 3. Agenda – Goals – Code quality – SOLID – Other principles – Demo – Conclusion – Q&A SOLID Software Design 3
    4. 4. Agenda – Goals – Code quality – SOLID – Other principles – Demo – Conclusion – Q&A SOLID Software Design 4
    5. 5. GoalsNOT our goal SOLID Software Design 5
    6. 6. GoalsMastery takes lots of practice – You can’t learn to surf by reading a book – Neither programming SOLID Software Design 6
    7. 7. Goals “The 10.000 hour rule” – Malcolm Gladwell SOLID Software Design 7
    8. 8. Goals• ShuHaRi – Shu: Traditional wisdom – Ha: Breaking with tradition – Ri: Transcendence SOLID Software Design 8
    9. 9. GoalsAfter this session – you will NOT suddenly write better codeBut… – you hopefully have some hooks to get better SOLID Software Design 9
    10. 10. Agenda – Goals – Code quality – SOLID – Other principles – Demo – Conclusion – Q&A SOLID Software Design 10
    11. 11. Code qualityIs this code quality?private static final String OID = "oId";private static final String TIME_INCIDENT = "timeOfIncident";private static final String EX_MSG = "exMsg";private static final String TECH_EX_MSG = "techExMsg";...mav.addObject(OID, oId == null ? "":oId);mav.addObject(TIME_INCIDENT, (new Date()).toString());mav.addObject(EX_MSG, e.getMessage() == null ? "":e.getMessage());mav.addObject(TECH_EX_MSG, e.toString()); SOLID Software Design 11
    12. 12. Code qualityIs this code quality?@Controllerpublic class StartController { @Autowired public StartController(SessionData sessionData, TransactionService txService, InitializerFactory initFactory, AuthorizationHandler authHandler, UIBinder uiBinder, StartValidator startValidator, WebApplicationContext ctx, RegistrationService regService) { //... SOLID Software Design 12
    13. 13. Code qualityIs this code quality? SOLID Software Design 13
    14. 14. Code qualityIs this code quality? SOLID Software Design 14
    15. 15. Code qualityIs this code quality?/** * This controller contains default Action and Render mappings, * used as fallback for handling invalid URLs. This prevents DOS * attacks, because a "no-handler-found“ Exception results in a * corrupt application state in WAS and can only be restored by * restarting the application. These handlers solve this problem. */@Controller@RequestMapping("VIEW")public class DefaultController { SOLID Software Design 15
    16. 16. Code qualityIs this code quality?/** * This controller contains default Action and Render mappings, * used as fallback for handling invalid URLs. This prevents DOS * attacks, because a "no-handler-found“ Exception results in a * corrupt application state in WAS and can only be restored by * restarting the application. These handlers solve this problem. */@Controller@RequestMapping("VIEW")public class WebSphereASDefaultHandlerController { SOLID Software Design 16
    17. 17. Code qualityTonight, code quality means OO Design – OOD is not free or easy, not even with Java/C# – A lot of structured programming out there! SOLID Software Design 17
    18. 18. Code qualityTonight, code quality means SOLID principles – Not about Object Oriented Modeling • (Person, User, Plane is-a Vehicle, etc) • Highlighting Nouns – But about Dependency Management SOLID Software Design 18
    19. 19. Code qualityTonight, code quality means Dependency Mgt – Because • We DON’T want rigid code • We DON’T want changes to cause ripple effects • We DON’T want fragile code • We DO want easily unit testable code • We DO want reusable code • We DO want readable code SOLID Software Design 19
    20. 20. Code qualityWhy dependency Management? – Because we don’t want code rot SOLID Software Design 20
    21. 21. Code qualityWhy dependency Management? – Refactor sprint SOLID Software Design 21
    22. 22. Code qualityWhy dependency Management? – Continuous refactoring SOLID Software Design 22
    23. 23. Agenda – Goals – Code quality – SOLID – Other principles – Demo – Conclusion – Q&A SOLID Software Design 23
    24. 24. SOLIDSOLID – First stated by Robert C. Martin in 1995 – “The Ten Commandments of OO Programming” SOLID Software Design 24
    25. 25. SOLIDSOLID: – Later documented in “Agile Software Development: Principles, Patterns and Practices” SOLID Software Design 25
    26. 26. SOLIDShort for: – SRP: Single Responsibility Principle – OCP: Open-Closed Principle – LSP: Liskov Substitution Principle – ISP: Interface Segregation Principle – DIP: Dependency Inversion Principle SOLID Software Design 26
    27. 27. Single Responsibility Principle“A class should have only one reason to change” – Theory – Simple example – Real world example – Considerations – Conclusion SOLID Software Design 27
    28. 28. Single Responsibility PrincipleTheory – A Class Should Only Have One Reason To Change – Also referred to with the term Cohesion (DeMarco, Page-Jones) – Separation of Concerns – Classes should have ONE well-defined responsibility SOLID Software Design 28
    29. 29. Single Responsibility Principle SOLID Software Design 29
    30. 30. Single Responsibility PrincipleSimple example – Database application interface specificationpublic interface Database { public void connect(String url); public void disconnect(); public ResultSet executeQuery(String query);} SOLID Software Design 30
    31. 31. Single Responsibility PrincipleSimple example – What if the protocol changes? – What if the connection management changes? – What if we want to implement pooling or caching? – We’ll need to change the database implementation in both cases SOLID Software Design 31
    32. 32. Single Responsibility PrincipleSimple example – How about this?public interface DatabaseConnection { public ResultSet executeQuery(String query);}public interface DatabaseConnectionManager { public DatabaseConnection connect(String url); public void disconnect(DatabaseConnection conn);} SOLID Software Design 32
    33. 33. Single Responsibility PrincipleSimple example – DatabaseConnection implementations handle querying – DatabaseConnectionManager implementations handle connections – We’ve managed to split two responsibilities SOLID Software Design 33
    34. 34. Single Responsibility PrincipleConsiderations – Should we split every class we create? No. – Will we end up with one-method classes? No. SOLID Software Design 34
    35. 35. Single Responsibility PrincipleConsiderations – If the application doesn’t require changing either of the coupled responsibilities at different times DON’T USE SRP – Don’t apply SRP if there are no symptoms – Treat it as a guideline – Be consistent in what you call a “Responsibility” • Split on functionality, domain, architecture, layers and do this in a consistent way SOLID Software Design 35
    36. 36. Single Responsibility PrincipleConclusion – Simplest SOLID principle, hardest to get right – Be critical deciding whether or not an SRP violation needs to be fixed – Stay pragmatic! – State management simplified by separating object lifecycles SOLID Software Design 36
    37. 37. Single Responsibility PrincipleQuestion: Real world usages of SRP? – Examples in Java API – Examples in GoF Design Patterns – Big abusers SOLID Software Design 37
    38. 38. Open-Closed Principle“Software entities should be open for extension,but closed for modification” – Theory – Simple example – Real world example – Considerations – Conclusion SOLID Software Design 38
    39. 39. Open-Closed PrincipleTheory – Helps preventing rigidity and cascading changes – Open for extension • Behaviour of a module can be extended – Closed for modification • Extending does not result in a source change for a module SOLID Software Design 39
    40. 40. Open-Closed Principle SOLID Software Design 40
    41. 41. Open-Closed PrincipleSimple Example – We are using this Rectangle objectpublic class Rectangle { private int width; private int height; public int getWidth() { return width; } public int getHeight() { return height; }} SOLID Software Design 41
    42. 42. Open-Closed PrincipleSimple Example – With this function we calculate area totalspublic class AreaCalculator { public int calculateTotalArea(Rectangle [] rectangles) { int totalArea = 0; for(Rectangle rectangle : rectangles){ totalArea += rectangle.getWidth() * rectangle.getHeight(); } return totalArea; }} SOLID Software Design 42
    43. 43. Open-Closed PrincipleSimple Example – Now we want to add a circle to the equationpublic class Circle { private int radius; public int getRadius() { return radius; }} SOLID Software Design 43
    44. 44. Open-Closed PrincipleSimple Example – What happens to the calculation?public double calculateTotalArea(Object [] objects) { double totalArea = 0; for(Object object : objects){ if(object instanceof Rectangle){ Rectangle rectangle = (Rectangle)object; totalArea += rectangle.getWidth() * rectangle.getHeight(); } if(object instanceof Circle){ Circle circle = (Circle)object; totalArea += circle.getRadius() * circle.getRadius() * Math.PI; } } return totalArea;} SOLID Software Design 44
    45. 45. Open-Closed PrincipleSimple Example – This is poor design (of course) – The calculate method is not closed for modification and not open for extension – Adding a Circle requires the developer to change the calculation code! SOLID Software Design 45
    46. 46. Open-Closed PrincipleSimple Example – Introducing Shape and extending itpublic abstract class Shape { public abstract double getArea();}public class Circle extends Shape { public double getArea() { return radius * radius * Math.pi; } …} SOLID Software Design 46
    47. 47. Open-Closed PrincipleSimple Example – Simplifies AreaCalculator substantially – Allows future extensionpublic class AreaCalculator { public double calculateTotalArea(Shape[] shapes) { double totalArea = 0; for (Shape shape : shapes) { totalArea += shape.getArea(); } return totalArea; }} SOLID Software Design 47
    48. 48. Open-Closed PrincipleSimple Example – The calculation is now Open for extension and closed for modification – Adding another shape to the equation no longer requires a change to the calculate implementation SOLID Software Design 48
    49. 49. Open-Closed PrincipleConsiderations SOLID Software Design 49
    50. 50. Open-Closed PrincipleConsiderations – Abstraction is key – So… should we just abstract everything? No. – Abstract elements that require frequent change – Overuse of abstractions can create clutter – Avoid premature abstraction SOLID Software Design 50
    51. 51. Open-Closed PrincipleConclusion – At the heart of Object Oriented design – Design using logical, useful abstractions – Add abstractions only when required – Expect having no changes in your code – Stimulate change (test, iterate) – Properly refactor code that’s affected by these changes SOLID Software Design 51
    52. 52. Open-Closed PrincipleQuestion: Real world usages of OCP? – Examples in Java API – Examples in GoF Design Patterns – Big abusers SOLID Software Design 52
    53. 53. Liskov Substitution Principle“If for each object o1 of type S there is an object o2 oftype T such that for all programs P defined in terms ofT, the behavior of P is unchanged when o1 issubstituted for o2 then S is a subtype of T” – Come again? SOLID Software Design 53
    54. 54. Liskov Substitution Principle“Subtypes must be substitutable for their basetypes” – Theory – Simple example – Real world example – Considerations – Conclusion SOLID Software Design 54
    55. 55. Liskov Substitution PrincipleTheory – Polymorphism problem – A extends B • This means A IS-A B • …but is this always true for A and B? SOLID Software Design 55
    56. 56. Liskov Substitution Principle SOLID Software Design 56
    57. 57. Liskov Substitution PrincipleSimple Example – Square extends Rectangle • Square IS-A Rectangle, right? – Difference between Square and Rectangle • Rectangle can have different height and width settings • Square has equal values for both SOLID Software Design 57
    58. 58. Liskov Substitution PrincipleSimple Example – So, this is correct then?class Rectangle { private int width; private int height; public Rectangle(int width, int height) { this.width = width; this.height = height; } // Setters left out for brevity}class Square extends Rectangle { // Initialize as a square public Square(int size) { super(size, size); }} SOLID Software Design 58
    59. 59. Liskov Substitution PrincipleSimple Example – Suppose we test the Square like thisSquare square = new Square(42);assertEquals(42, square.getWidth()); // Oksquare.setHeight(50);// Width should be the same as height, and we changed it!assertEquals(50, square.getWidth()); // Whoops! – Our square suddenly is a 42 by 50 Rectangle! SOLID Software Design 59
    60. 60. Liskov Substitution PrincipleSimple Example – Fixing is easy, but is this really the way to go?class Square extends Rectangle { public void setWidth(int width) { super.setWidth(width); super.setHeight(width); } public void setHeight(int height) { super.setHeight(height); super.setWidth(height); }} SOLID Software Design 60
    61. 61. Liskov Substitution PrincipleSimple Example – Maybe better to do thisclass Square extends Shape { // Immutable private final int size; public Square(int size) { this.size = size; } @Override public int getHeight() { return size; } @Override public int getWidth() { return size; }} SOLID Software Design 61
    62. 62. Liskov Substitution PrincipleConsiderations – The IS-A relationship not always applies in code • A square is a rectangle in the real world • A square is not a rectangle in code – contract breaks when square doesn’t override rectangle behaviour – Immutability can make a difference • public Rectangle(int width, int height); • public Square(int size); • If both are immutable, Rectangle really IS-A Square! SOLID Software Design 62
    63. 63. Liskov Substitution PrincipleConclusion – Rule of thumb • Instead of: A IS-A B, use: A is substitutable by B – Inherit from a more abstract supertype if needed • Rectangle and Square could both inherit from Shape • Shape should enforce no rules for width and height – Should you prevent LSP violations at all cost? No. • What if you only have a method that draws Rectangles • Will the LSP violation be a problem then? SOLID Software Design 63
    64. 64. Liskov Substitution PrincipleQuestion: Real world usages of LSP? – Examples in Java API – Examples in GoF Design Patterns – Big abusers SOLID Software Design 64
    65. 65. Interface Segregation Principle“Clients should not be forced to depend onmethods that they do not use” – Theory – Simple example – Real world example – Considerations – Conclusion SOLID Software Design 65
    66. 66. Interface Segregation Principle SOLID Software Design 66
    67. 67. Interface Segregation PrincipleSimple Example – Interface definition for a worker doing workpublic interface Worker { public void work(); public void eat();} – Implementation for a generic employeepublic class Employee implements Worker { public void work() { // do work stuff } public void eat() { // eat lunch, keep up strength ;) }} SOLID Software Design 67
    68. 68. Interface Segregation PrincipleSimple Example – Robots are also part of the businesspublic class Robot implements Worker { public void work() { // Work (without union breaks } public void eat() { // Wait, what? }} – But they don’t eat lunch – Still, eat() has to be implemented SOLID Software Design 68
    69. 69. Interface Segregation PrincipleSimple Example – Split up the interfaces into sensible piecespublic interface NutritionConsumer { public void eat();}public interface Worker { public void work();} SOLID Software Design 69
    70. 70. Interface Segregation PrincipleSimple Example – Implement the interfaces as neededpublic class Employee implements Worker, NutritionConsumer { public void work() { } public void eat() { }}public class Robot implements Worker { public void work() {}} SOLID Software Design 70
    71. 71. Interface Segregation PrincipleSimple Example – Class dealing with Worker objectspublic class WorkloadManager { public void putWorkerToWork(Worker worker) { worker.work(); }} – Can deal with both robots and employees – Doesn’t need to be concerned with the nutritional needs of the Employee type workers SOLID Software Design 71
    72. 72. Interface Segregation PrincipleConsiderations – Avoid coupling between interfaces and clients – Clients should only depend on methods they use – Separation reduces the risk of changes cascading to implementing classes that do not have a need for those methods SOLID Software Design 72
    73. 73. Interface Segregation PrincipleConclusion – Separate interfaces when it makes sense – Don’t overdo it! • Prevent classes having to implement many interfaces • Prevent one-method interfaces – Common sense is key (again) • Split up interfaces as soon as clients show the need to do so SOLID Software Design 73
    74. 74. Interface Segregation PrincipleQuestion: Real world usages of ISP? – Examples in Java API – Examples in GoF Design Patterns – Big abusers SOLID Software Design 74
    75. 75. Dependency Inversion Principle“High-level modules should not depend on low-level modules directly, but through abstraction”“Abstractions should not depend on details,details should depend on abstractions” – Theory – Simple example – Real world example – Considerations – Conclusion SOLID Software Design 75
    76. 76. Dependency Inversion Principle SOLID Software Design 76
    77. 77. Dependency Inversion PrincipleSimple Example – Application that monitors system statuspublic class SystemStatus { private HeatGauge gauge; public void checkTemperature() throws OverheatingException { if(gauge.actualTemperature() > 55) { throw new OverheatingException(); } }} SOLID Software Design 77
    78. 78. Dependency Inversion PrincipleSimple Example – HeatGauge implementationpublic class HeatGauge { public int actualTemperature() { // Do some measuring and return the results }} SOLID Software Design 78
    79. 79. Dependency Inversion PrincipleSimple Example – Systemstatus directly depends on HeatGauge – Changes to HeatGauge can affect SystemStatuspublic class SystemStatus { private HeatGauge gauge = new HeatGauge(); public void checkTemperature() throws OverheatingException { if(gauge.actualTemperature() > 55) { throw new OverheatingException(); } }} SOLID Software Design 79
    80. 80. Dependency Inversion PrincipleSimple Example – Abstract away the dependencypublic interface HeatGauge { public int actualTemperature();}public class HeatGaugeImpl implements HeatGauge { public int actualTemperature() { // Do some measuring }} SOLID Software Design 80
    81. 81. Dependency Inversion PrincipleSimple Example – Use the new abstractionpublic class SystemStatus { // Less dependent by using the interface private HeatGauge gauge = new GaugeImpl(); public void checkTemperature() throws OverheatingException { if(gauge.actualTemperature() > 55) { throw new OverheatingException(); } }} – Better, but not perfect SOLID Software Design 81
    82. 82. Dependency Inversion PrincipleSimple Example – Improving the examplepublic class SystemStatus { private HeatGauge heatGauge; public SystemStatus(HeatGauge heatGauge){ this.heatGauge = heatGauge; } public void checkTemperature() throws OverheatingException { if(heatGauge.actualTemperature() > 55) { throw new OverheatingException(); } }} – Abstracts away the implementation used to gauge the temperature SOLID Software Design 82
    83. 83. Dependency Inversion PrincipleConsiderations – Clients should ‘own’ the interfaces used to access low-level modules – Not the same as Dependency Injection (DI) • Dependency Inversion – Using abstractions to achieve loose coupling – Ownership should be at client level • Dependency Injection – Design pattern to implement loose coupling SOLID Software Design 83
    84. 84. Dependency Inversion PrincipleConclusion – Maybe the most relevant of all SOLID principles – Allows robust code to be written using abstractions – Dependency Inversion • Relevant when designing functionality – Dependency Injection • Relevant when implementing functionality – Do all classes need an interface? No. SOLID Software Design 84
    85. 85. Dependency Inversion PrincipleQuestion: Real world usages of DIP? – Examples in Java API – Examples in GoF Design Patterns – Big abusers SOLID Software Design 85
    86. 86. Agenda – Goals – Code quality – SOLID – Other principles – Demo – Conclusion – Q&A SOLID Software Design 86
    87. 87. Other principlesNot SOLID, but just as important! – REP: Release reuse Equivalency Principle – CCD: Common Closure Principle – CRP: Common Reuse Principle – ADP: Acyclic Dependencies Principle – SDP: Stable Dependencies Principle – SAP: Stable Abstractions Principle – From the same book as SOLID SOLID Software Design 87
    88. 88. Other principlesNot SOLID, but just as important! – REP: Release reuse Equivalency Principle – CCD: Common Closure Principle – CRP: Common Reuse Principle – About package cohesion SOLID Software Design 88
    89. 89. Other principlesNot SOLID, but just as important! – ADP: Acyclic Dependencies Principle – SDP: Stable Dependencies Principle – SAP: Stable Abstractions Principle – About package coupling SOLID Software Design 89
    90. 90. Agenda – Goals – Code quality – SOLID – Other principles – Demo – Conclusion – Q&A SOLID Software Design 90
    91. 91. ConclusionDemo – Small web application to demo the ideas SOLID Software Design 91
    92. 92. Agenda – Goals – Code quality – SOLID – Other principles – Demo – Conclusion – Q&A SOLID Software Design 92
    93. 93. ConclusionMaster the SOLID principles – Use it in your communications – Use it to challenge your design/yourself – Applicable to modules, libraries, components... – But don’t be dogmatic about it – Don’t write SOLID, just because you can – Try to see the disadvantages too! – Don’t just believe the hype! SOLID Software Design 93
    94. 94. ConclusionSOLID principles are no hard rules – Definitely no hard rules! – Also no goals, just a means to an end – There are more principles – Principle of least Knowledge – Premature optimization is the root of all evil – Composition over Inheritance – K.I.S.S. / Y.A.G.N.I. SOLID Software Design 94
    95. 95. ConclusionDon’t be dogmatic – Even Uncle Bob said this – http://blog.objectmentor.com/articles/2009/02/06/on – In response to – http://www.joelonsoftware.com/items/2009/01/31.ht SOLID Software Design 95
    96. 96. Q&AAny questions left? SOLID Software Design 96

    ×