SOLID is an acronym for a set of important design principles. Paired together they create a framework for worry free code, and by “worry free” I am speaking of code that would trouble you if any changes needed to be made. In the world today things are constantly changing and being updated and so should your code. If that’s the case then any code you write should have the ability to be edited without causing a complete overhaul of your whole program. Basically what you want to avoid is trickle down effects, and unlike trickle down economics, this is real. If you change one thing or responsibility of a class or variable and that causes a cascade of continuous changes and troubles, then you are experiencing this trickle down effect. To help with this issue is the first design principle in the acronym, Single Responsibility Principle.
Single Responsibility Principle is exactly what it sounds like. Give your classes and methods a sole responsibility so that if they are changed it will only effect that method or classes responsibility. If a class or method handles multiple responsibilities then changing the design of one part may be cause to change the entire entity.
A crude example would be a Rectangle Class. Let us say you have a constructor to build a rectangle object and all it does is take arguments for height and width. However, you also add if and else statements in the constructor to see if the dimensions make a square and printing a confirmation message if it is. Perhaps you even write “if (myShape.isSquare())..” to send the object to a method to, but this is giving the constructor more than one responsibility. If you decide to change the placement of the square check then there will either be duplicated code or you will have to edit the constructor to pass the isSquare result to other methods. Doing any of this would result is test case changes if you were testing the code. In this scenario it is best to have the constructor just be the constructor and to dedicate the square check to its own method like isSquare. In this case if changes were made then only a single class would require changes and not several that are connected in a convoluted fashion.
I think the Single Responsibility Principle is a must know. I remember beginning coding is CS140 and Data Structures and I would try to get as much done in as few methods as possible by cramming in multiple functions into them. I thought the less methods the better but I was so wrong, it’s worth so much more to have many separate methods and classes that each have a sole function. This way code is organized, easy to arrange, and simple to implement or change.
SOLID Design Principles Explained: The Single Responsibility Principle. (2018, December 17). Retrieved from https://stackify.com/solid-design-principles/
From the blog cs@worcester – Zac's Blog by zloureiro and used with permission of the author. All other rights reserved by the author.