An adventure in SOLID – S

Recently I started looking at programming design principles and patterns and I came across SOLID. SOLID is a set of design principles for producing easily maintainable code in any OOP capable language. I will be taking a look over what SOLID is and what changes need to be made to your code to make it in line with the ideals these principles put forward.

S is for…

Single responsibility principle (SRP)

Wikipedia says that:

In object-oriented programming, the single responsibility principle states that every class should have a single responsibility, and that responsibility should be entirely encapsulated by the class. All its services should be narrowly aligned with that responsibility.

In short if you write a class that displays JSON from a file on disk then the responsibility for loading the file should be the responsibility of one class and display of the JSON should be down to another class. If you lump them together then when you write that class that loads an XML file and turns it into a PHP array, you will be repeating your file loading code and therefore have to maintain two copies of that particular code base.

Here is my first attempt to produce a bit of non-SRP and a bit of SRP code:

non-SRP


Up to date file here.

SRP


Up to date file here.

As you can see from a cursory glance the non-SRP class combines the act of connecting to a database and running a query with the act of producing a list of tasks. These responsibilities should not be in the same class as this will cause problems when maintaining the code base.

The SRP “compliant” file has two classes declared, one to connect to a database and run queries and another to deal with the tasks themselves. This design means that should you decide to start logging database connections with your db class you can do so without altering the task class.

Conclusion

Single responsibility principles allow for clear declarations of the methods and properties of classes. Creating a clear boundary between your classes is a must if you want to maintain a code base that can be reused over and over or that is implemented in a long running project.

So now I know how to do this I best get on with the other elements of SOLID. O is next so stay tuned for a look at the Open/closed principle.

This post has been viewed 1033 times.

One thought on “An adventure in SOLID – S

Leave a Reply

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