An adventure in SOLID – O

Part two in my adventure into SOLID design principles. Here we take a look at the Open/Close Principle, this means that classes are open to extension however closed to modification.

The point of this is becomes clear when you consider a logging system. If you start off with a logging system that logs to a file on disk (and you are following the principles of SRP), if you decide that you would like to start logging to a database or SNMP then that would count as a new feature. A new feature means that you need to make a new class. This class should extend the functionality of the logging class so that we are not directly adding the feature into our logging code.

I have put an example together below, I hope this will clarify my description…


So, the example above shows how not to do things, not only does it have two responsibilities it is also vulnerable to new features having to be added to it. If you wanted to start logging to syslog then you would need to create a new method to do so, however if you make the log class extendable then you can log to any media you like. Here is an example that supports logging to a file or to syslog.

This is a very basic overview of OCP and I will more than likely put up some more posts as my understanding builds.

This post has been viewed 1290 times.

Leave a Reply

Your email address will not be published. Required fields are marked *