Search code examples
c#oopsolid-principles

OCP, is the client or the abstract class hiearchy open-closed?


I am sorry for a possibly confusing title, I was not able to find a more suitable one. I am learning about the open closed principle. Some authors mention that this is actually OCP - the base class is closed and is being extended by new stuff in the derived classed:

abstract class A {}
class B : A {}
class C: {}

Then others say that it is actually the code dependent on those classes which does not need to be changed anymore, because it relies on abstractions. So I am a bit confused.


Solution

  • There is an example that I like: http://www.oodesign.com/open-close-principle.html

    It's written in Java, but nonetheless, hope that's readable. I also love Uncle Bob Martin seminar on SOLID principles.

    The thing about OCP is to make code your code extendable to new functionality. Now to you example, let's say you have:

    abstract class A {
       public string GetString(string str) {
          return Format(str);
       }
    
       public virtual string Format(string str) { return str; };
    }
    
    class B: A {
       public override string Format(string str) { return $"%{str}%"; }
    }
    

    Let's say that abstract class A is in the library and you are using it, but want to extend with some formatting method Format. Now, it's not the best real world example, you probably would use formatting class for that purpose. But about OCP, we have closed for modifications class A and we can extend it. Another thing is not to follow Liskov Substitution Principle and not break Format method for A class.