The Open-Closed Principle: Some Intepretations
I am a fan of the SOLID principles, I think if you use them as guidance when you’re doing OOP you can deliver flexible, testable and scalable solutions.
That said, one of the principles that I haven’t quite got totally to grips with is the Open-Closed Principle.
I was talking with a colleague and they had a very different interpretation than I did. Let’s have a look at each of them.
My Interpretation
Take this class as an example (stolen from the Laracasts video).
class AreaCalculator
{
public function calculate(Square $square)
{
return $square->length * $square->height;
}
}
This class calculates the area of a Square
, but it’s currently not very flexible and it violates the OCP because we’d have to modify the internals of the class every time we need to extend this class to calculate the areas for other shapes. Like this:
class AreaCalculator
{
public
...