This time around I’m continuing my discussion of the SOLID principles with O.
The O in SOLID - The Open-Closed Principle
Let's continue our discussion of the SOLID principles. Today we'll look at the O in SOLID: the Open-Closed Principle.
First proposed by Bertrand Meyer in 1988, this goes like this: Software entities (such as classes and functions) should be open for extension but closed for modification.
Seems a weird way of saying it, but in essence this is saying that any class (or whatever) you write should be written in such a way that it can be used as is, be extended if need be, but never needs to be modified. In other words, use the class in any way you need but modifying its behavior comes by adding new code, never by modifying or deleting the old.
How on earth do we do this? The answer is through abstractions. Back to my example binary tree painting code I'm using to discuss these principles. If you remember from last time, I split the tree painting code into code that navigated the tree and code that painted the nodes and edges.
There is still a problem though: if my tree navigation code holds a reference to the node painting code, I'm no further forward than I had been. I can still only draw trees as I did before. What if I had another graphics library? What if I had another surface (paper? bitmap?) that I wanted to draw on?
Unfortunately, as I wrote it, I'd have no option but to rewrite large chunks of my node painting code in order to support such scenarios.
What should I have done in the first place? Abstracted out the graphics context so that it covers things like create the context, draw a line from A to B, draw a filled circle at X, and so on. Once I have that -- for example as an interface if I were using C# -- then I can write a concrete class that fulfills the interface and pass that in to my tree painting code. If I need to draw on paper, I again just write a class that implements the interface and away I go. No need to change the tree painting code at all: just abstract out the main features of the painting code and supply the instance of a concrete class at run-time.
Abstractions are good. Referencing concrete classes is bad.
You can watch the video here.
Simple enough: write your classes in such a way that others can use them as is and don’t have to crack open the source code. Kind of puts the kibosh on the whole
sealed keyword in C# if you ask me. Another way of looking at this is that it indicates using composition in your class/object model.
For Uncle Bob’s chapter on the Open-Closed Principle, click here for the PDF.
(Here are the links to the other principles: S O L I D.)