0

Open-Closed principle is one of the five SOLID principles of object-oriented design. It states that "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification".

But recently most programming languages are providing a way to finalize classes such that it won't be inherited in future by providing keywords such as final. Some languages like Kotlin have their classes by default final (aka opt-in open).

I have also read some articles which states that interface inheritance must be preferred over implementation inheritance with valid reasoning like fragile base class problem. But OCP tells that classes should be open for extension. So should I consider declaring my classes open? or final? Which is a good practice in general?

Sourav Kannantha B
  • 2,860
  • 1
  • 11
  • 35

2 Answers2

0

I think no!

The main reason behind this is stated below.

The open-closed principle attacks this in a very straightforward way. It says that you should design modules that never change. When requirements change, you extend the behavior of such modules by adding new code, not by changing old code that already works."

So we can say it's the structural format for any code!

0

Inheritance is just one of the techniques used to fulfil OCP. Strategy pattern, decorator pattern, ordinary composition, parametric polymorphism and other techniques can be used to achieve those goals too. Inheritance will always be an option but should be avoided if possible, as appropriate.

lkatiforis
  • 5,703
  • 2
  • 16
  • 35