SOLID Principles: Write SOLID programs; Avoid STUPID programs

Shravan Kumar B
8 min readOct 18, 2020

“Think Twice, Code Once”

Hi everyone! This is a revised version of my article from my personal blog.

Previously, in my last article, I had explained some of the must-know fundamental programming principles, which are applicable in any programming paradigm that you follow. Be it Functional or Object-Oriented paradigm/programming, those serve as the primary fundamentals.

This article purely speaks of another 5 design principles, most specifically hold good to problems that can be solved using the OOPs paradigm. With the rise of the OOPs paradigm, brought new designs and techniques of writing the solution to a problem.

“Think Twice, Code Once”

Similarly, on a larger scale, this technique caused some flaws in the solution we design and write, which often we fail to recognize the bugs added in the form of STUPID code.

As I started programming in Typescript standards, implementing OOPS, had become easier, better, smaller, and cleaner. I realized one thing after moving from Functional Paradigm to OOPs paradigm, that knowingly or unknowingly we end up implementing some sort of anti-patterns into our codebase.

What’s a STUPID codebase?

A STUPID codebase is that codebase which has flaws or faults, which affect the maintainability, readability or efficiency.

Anti-Pattern Code == STUPID Code

What causes STUPID codebase?

Why be STUPID, when you can be SOLID
  • Singleton: Violation of Singleton basically decreases the flexibility and reusability of the existing code, which deals with the object creation mechanism.
    It is an anti-pattern, where we define a class and its object in the same script/file and export the object for reusability. This is pattern is not wrong, but using it everywhere inappropriately is an symptom sick codebase.
  • Tight-Coupling: Excessive coupling/dependency between classes or different separate functionality is a code smell, we need to be very careful about it while we are developing or programming.
    We can figure tight-coupling when a method accesses the data of another object more than its own data or some sort of functional chaining scenarios.
  • Untestabiility: Unit Testing is a very important part of software development where you cross-check and test if the component you built is functioning exactly the way expected. It is always advised to ship a product only after writing test cases. Shipping an untested code/product is very much similar to deploying an application whose behavior you are not sure about.
    Apart from Unit testing, we have other tests like Integration testing, E2E testing, and so on, which are done based on their use cases and necessity.
  • Premature Optimizations: Avoid refactoring code if it doesn’t improve the readability or performance of the system for no reason.
    Premature optimization can also be defined as trying to optimizing the code, expecting it to improvise the performance or readability without having much data assuring it and purely weighing upon intuitions.
  • Indescriptive Naming: Descriptive Naming and Naming Conventions are two important criteria. Most of the time, naming becomes the most painful issue.
    After some time when you or another developer visits the codebase, you would be asking the question ‘What does this variable do?’. We fail to decide what would be the best descriptive name that can be given to a variable, class, class object/instance, or function. It is very important to give a descriptive name, for better readability and understandability.

These flaws were often overlooked knowingly or unknowingly, for which SOLID principles served as the best cure.

So, you wondering now what SOLID principles hold and how does it solve the issues caused due to STUPID postulates. These are programming standards that all developers must understand very well, to create a product/system with good architecture.
SOLID principles can be considered as remedies to the problems caused due to any of the STUPID flaws in your codebase.
Uncle Bob, otherwise known as Robert C Martin, was the Software Engineer and Consultant, who came up with the mnemonic acronym SOLID in his book “Clean Coder”. Let’s explore a little more on SOLID principles in detail,

Single Responsibility Principle (SRP)

A class, method, or function should undertake the responsibility of one functionality. In simpler words, it should carry out only one feature/functionality.

A class should only have a single responsibility, that is, only changes to one part of the software’s specification should be able to affect the specification of the class.
- Wikipedia

In the OOPs paradigm, one class should only serve one purpose. This does not mean that each class should have just one method, but the methods you define inside a class should be related to the responsibility of that class.

Let us look into it using a very basic example,

The problem in the above implementation is that, methods that deals with business logic and related to database calls are coupled together in same class, which violates the Single Responsible Principle.

The same code can be written ensuring the SRP is not violated, by dividing the responsibilities for dealing business logic and database calls separately, as shown in the below instance

Here, we are ensuring a specific class solves a specific problem; UserService dealing with business logic and UserRepo dealing with database queries/calls.

Open-Closed Principle (OCP)

This principle speaks about the flexible nature of the code you write. As the name stands for itself, the principle states that the solution/code you write should always be for extensions but for modifications.

Software entities … should be open for extension, but closed for modification.
-Wikipedia

To put it up in simpler words, the code/program you write for a problem statement, be it a class, methods, or functions, should be designed in such that, to change their behavior, it is not necessary to change their source code/reprogram.

If you get additional functionality, we need to add that additional functionality without changing/reprogramming the existing source code.

The major setback with the above approach is that again if a newer way of sending a notification or combined notifying mechanism is needed, then we need to alter the definition of the sendNotification().

This can be implemented ensuring the SOLID principle not being violated, as shown below,

As you see in the above example, when you needed another requirement where you had to send both email and mobile notification, all I did was adding another function sendEmailwithMobileNotification() without changing the implementation of previous existing functions. That’s how simple it is, making an extension of features.

Now, moving on to the next important principle, called as Liskov Substitution principle.

Liskov Substitution Principle (LSP)

This principle is the trickiest one. Liskov Substitution Principle was introduced by Barbara Liskov in her paper called “Data Abstraction”.
By now, you already must have known that this principle has to do with the way we implement Abstraction.

Recalling, what is abstraction/data abstraction? In simplest words, hiding certain details and showing essential features.
Example: Water is composed of Hydrogen and Oxygen, but we see is a liquid matter (Abstraction)

“Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.”
-Wikipedia

According to the OOP paradigm, child classes should never break the parent class type definition.
To put it in even simpler bits, all subclass/derived classes should be substitutable for their base/parent class. If you use the base type, you should be able to use subtypes without breaking anything.

What we can draw from the violation, causes tight coupling and less flexibility to handle changed requirements. Also, one thing that we take away from the above example and principle is that OOP is not only about mapping real-world problems to objects; it is about creating abstractions.

Interface Segregation Principle (ISP)

This principle deals with the demerits and issues caused when implementing big interfaces.

“Many client-specific interfaces are better than one general-purpose interface.”
-Wikipedia

It states that we should break our interfaces into granular small ones so that they better satisfy the requirements. This is necessary so as to reduce the amount of unused code.

Here we see that one interface ICommodity is created for the items/commodity in the shop; which is incorrect.

This principle focuses on dividing the set of actions into smaller parts such that the Class executes what is required.

Interface Segregation Principle (ISP)

This principle states that we should depend upon abstractions. Abstractions should not be dependent on the implementation. The implementation of our functionality should be dependent on our abstractions.

One should “depend upon abstractions, [not] concretions.”
— Wikipedia

Dependency Injection is very much correlated to another term called Inversion of Control. These two terminologies are can be explained differently in two situations.

  1. Based on Framework
  2. Based on Non-Framework ( Generalistic )

Based on programming in Framework, Dependency Injection is an application of IoC, i.e., Inversion of Control. Technically speaking, Inversion of Control is the programming principle, that says invert the control of the program flow.

To put it up in simpler words, the control of a program is inverted, i.e., instead of the programmer controlling the flow of the program. IoC is inbuilt with the framework and is a factor that differentiates a framework and library. Spring Boot is the best example.

Voila! Spring Boot developers! Inversion of Control made sense!! Didn’t it?

Note: For all Spring Boot developers, just like how annotation take control over your program flow

Based on the general perspective, we can define IoC as the principle that ensures, “An object does not create other objects on which they rely to do their work”.
Similarly, based on the general perspective, DIP is a subset principle to IoC, that states define interfaces to make it easy to pass in the implementations.

If you look into the above examples, the Object creation is dependent on the interface and not on the class.

These are the OOPs Paradigm Programming Principle that makes your code more readable, maintainable, and clean.

As a developer, we should avoid trying to write dirty or STUPID code. These are the basic things, we need to keep in mind during the development.

SOLID is no panacea or remedy for all the problems. Some problems in Computer Science can be solved using basic engineering techniques. SOLID is one such technique that helps us maintain a healthy codebase and clean software. The benefits of these principles are not immediately apparent but they become noticed and visible over time and during the maintenance phase of the software.

As a developer, it is my suggestion that every time you design or program a solution, ask yourself “Am I violating the SOLID principles?”, if your answer is YES, too long, then you should know that you are doing it wrong.
One thing that I can assure is, these principles are always going to help us write better code.

If you like the article, hit the like button, share the article and subscribe to the blog. If you want me to write an article on specific domain/technology I am provisioned in, feel free to drop a mail at shravan@ohmyscript.com

Stay tuned for my next article.

That’s all for now. Thank you for reading.

Signing off until next time.
Happy Learning.

Originally published at OhMyScript on October 6, 2020.

--

--

Shravan Kumar B

A caffeine-dependent life-form yearning about Technology | Polyglot Developer | Open Source Lover