Upgrade to Pro — share decks privately, control downloads, hide ads and more …

SOLID - Open Closed Principle

SOLID - Open Closed Principle

Avatar for Samir Behara

Samir Behara

April 28, 2018
Tweet

More Decks by Samir Behara

Other Decks in Technology

Transcript

  1. Session Objectives and Takeaways  OCP Definition by Bertrand Meyer

    & Robert C. Martin  Understand the Problem and various Code Smells  How OCP comes to the rescue?  Understand Fundamental Concepts  Exception scenarios for OCP Principle  How to refactor your code using OCP?
  2. Open for Extension Closed for Modification Must be able to

    satisfy changing requirements and support new features. Must be able to extend behavior without editing existing code.
  3. Once a class is deployed to Production or other clients

    start using it, you should not make changes to that class.
  4. RED GREEN REFACTOR Write a failing unit test recreating the

    bug Modify existing code so that unit test passes. Enhance the code without changing behavior. Defects/Bug Fixes TDD
  5. Client Awareness Change is allowed to a class as long

    as it does not require change to any client using it. Loose Coupling Tight Coupling
  6. Types of Extension Points Implementation Inheritance Interface Inheritance Rely on

    Abstractions – Abstract Base Classes and Interfaces
  7. Virtual Methods A lass that arks o e of its

    e ers as virtual is Ope to E te sio . Virtual methods have an implementation but can be overridden in the derived class. Virtual method Abstract method Can provide a default implementation. Cannot have an implementation. If it is good enough, Child classes can use it or else override it. Child class must give their own implementation. Can exist on abstract or non- abstract class. Can only exist on an abstract class.
  8. Why Abstract Class? Move the common functionalities into the Base

    class. You do not want the base class to be instantiated. Code Maintainability is easier.
  9. public class Person Behavior - Jump public class Monkey :

    Person Behavior – Person Writes Code Behavior – Monkey Writes Code ?? public class Monkey
  10. Why Interfaces? Interfaces are purely abstract – no implementation, only

    declarations. Interfaces describe functionality whereas Class describes traits. Interfaces separate definition of objects from its implementation. Interfaces helps to develop loosely coupled systems. X Y X Y Interface
  11. Open Closed Principle – Benefits E isting fun tionalit won’t

    reak No need to change working code No need to fix broken unit tests New classes have no legacy coupling, hence less likely to create issues Move changes to Production faster. Build code that allows changes over time