SOLID Principles

Photo by Samuel Penn on Unsplash

SOLID Principles

The core of writing clean code

·

2 min read

I decided to start writing on my dev blog again awhile back but havent had the energy to do so. As I was reviewing the SOLID concepts, I felt happy that I can relate to it more compared last year when I first heard about it. Now, even with its simplicity - 5 principles that could be summarized with a 5 letter acronym, its kind of hard to remember vividly. I thought writing a blog would help me with it. I would be writing, compiling, my understanding to each of these principles.

Single Reponsibility Principle

SRP states that every class should have distinct functionality or role. Say we want to implement a functionality where a given string is supposed to be printed to console, sent to the database, and sent to a server. To follow SRP, we must not implement all these to one class but rather implement a class for each of them.

Open-Close Principle

OCP states that classes should be (open) extendable but closed for revisions. This means that is we are to add new functionality to a class, we should not be modifying the existing logic in the class. This could be implemented with the help of interfaces.

Liskov Substitution Principle

LSP somehow provides a restriction on how to implement polymerphism. The sub classes should be suitable for the base class. This could be interpreted in a lot of ways as writing classes is very flexible. However, I think the best way to understand this is that all the public methods and public properties of a subclasses should function and must represent data NOT deviating from their original behavior and functionality in the base class. At the simplest understanding, it tells us that we should mind the public methods and properties of a subclass as we are overwriting (modifying) them.

Interface Segregation Principle

ISP is more lowkey, it is like SRP but for interfaces. Many interfaces is better than one interface. It is like SRP such that one interface should be implementing a specific functionality. So if we have an interface that is to implement multiple functionalities (i.e. writing to a file and sending to a server), that interface should be executing sub interfaces where every sub interface implements a specific functionality.

Dependency Inversion Principle

SRP is the goal of OOP while DIP is the mechanism to do so. This provides a restriction on the manner we are writing classes. It states that are classes should not be depending on concrete classes. It should depend instead on abstract classes or interfaces.

This blog is my takeaway from reading the blog: freecodecamp.org/news/solid-principles-expl..