Graduate Program KB

Chapter 8 - The Open-Closed Principle

A Software artifact should be open for extension but closed for modification

A Thought Experiment

  • An application that displays financial summary on a web page, with negative numbers rendered in red

  • The stakeholders asks for the report to be printed on a black and white printer

  • New code must be written to do this, but how much of the old code needs to change?

    • Good software architecture would reduce the amount of code changes needed to a minimum
    • Can be done by following the single responsibility principle and dependency inversion principles
  • Essentially, there are 2 responsibilities

    1. Calculating the reported data
    2. Presentation of that data
    • If both are seperated, then you can independently change them without worrying about causing changes in both
  • Component A is protected from changes in Component B, then Component B depends on Component A.

  • Hierarchy of Protection

    • Interactors are high level concepts, and are most protected
      • Contains the business rules and deals with the central concern
    • Controllers
      • Peripheral to interactor but central to the View Component
    • Presenters
    • Views are low level concepts, least protected

Information Hiding

  • Transitive dependencies are indirect dependency relationship between components. It is a violation of a general principle, entities should not depend on things they don't directly use.
  • Have to protect changes on both ends for entities rather than protecting 1 entity from another.
    • Example: Protect Interactor from changes to Controller, and also protect Controller from changes in Interactor

Conclusion

  • Make the system easy to extend without causing huge changes
  • Partition system into components and have a hierarchy arranging them into high and low level concepts
  • Arranging components into a dependency hierarchy to protect high level components from changes in low level components