Mastering Clean Code: A Beginner’s Guide to SOLID Principles

Mastering Clean Code: A Beginner’s Guide to SOLID Principles




When you’re new to programming, your main goal is often to ensure your code works. However, as you gain more experience, you’ll find that creating code that is easy to read, maintain, and improve is just as crucial. This is where the SOLID principles come into play.
These five principles help you write code that is cleaner and more reliable.

Introduction to SOLID Principles:

The SOLID principles were first introduced by the famous Computer Scientist Robert J. Martin (Author of Clean Code and Clean Architecture, a.k.a Uncle Bob) in his paper in 2000. However, Michael Feathers introduced the acronym later.
The acronym stands for:
  • S — Single Responsibility Principle (SRP)
  • O — Open/Closed Principle (OCP)
  • L — Liskov Substitution Principle (LSP)
  • I — Interface Segregation Principle (ISP)
  • D — Dependency Inversion Principle (DIP)
These principles serve the same purpose: to create understandable, readable, and testable code that many developers can collaboratively work on. Let’s break down these principles in a simple way, with examples for each.

Single Responsibility Principle (SRP)

A class should have only one reason to change, meaning it should have only one job or responsibility.
Let’s say you have a class ‘User’ which deals with authentication and user profile updates like this:
class User {  
    authenticate_user(username,password){  
        //Login Logic  
    }  
    update_profile(user_id,update_data){  
        //Profile update Logic  
    }  
}
This class violates the SRP mentioned above as it has two responsibilities and thus, two reasons to change. To avoid that, we can divide this class into two separate classes like this:
class UserAuthentication {  
    authenticate_user(username,password){  
        //Login Logic  
    }  
}  
  
class UserProfile {  
    update_profile(user_id,update_data){  
        //Profile update Logic  
    }  
}
Each class has a well-defined responsibility and only one reason to change.
Additionally, it simplifies version control and collaboration by leaving only one reason for files to be modified. This reduces the likelihood of conflicting changes within a single file and leads to fewer merge conflicts.

Open/Closed Principle (OCP)

Software entities like classes, modules, and functions should be open for extension but closed for modification.
Modification means changing the code of an existing class, and extension means adding new functionality.
For example, you have a class ‘Shape’ which has a method to calculate the Area:
class Shape {  
    claculateArea(shape){  
        if(shape.type ='circle'){  
            return 3.14 * (shape.radius ** 2)  
        }  
        else if(shape.type = 'square'){  
            return shape.side ** 2  
        }  
    }  
}
If you want to add a new shape, you will have to modify ‘calculateArea’ which is against OCP. To solve this, you can use inheritance like this:
class Shape {  
    claculateArea(){}  
}  
  
class Circle extends Shape {  
    claculateArea(){  
        return 3.14 * (radius ** 2)  
    }  
}  
  
class Square extends Shape {  
    claculateArea(){  
        return side ** 2  
    }  
}
Open/Closed Principle helps us maintain the quality of our code because modifying the existing code introduces risks of creating potential bugs. Therefore, It is best practice to avoid modifying the tested and reliable code and to use OOP concepts like inheritance to extend it.

Liskov Substitution Principle (LSP)

Objects of a superclass should be replaceable with objects of a subclass without affecting the functionality.
This means that if you have a base class and a derived class, you should be able to use instances of the derived class wherever instances of the base class are expected, without breaking the application.
For example, you have two classes ‘Vehicle’ and ‘Bicycle’ like this:
class Vehicle {  
    startEngine() {  
        console.log('Starting the Engine')  
    }  
}  
  
class Bicycle extends Vehicle {  
    startEngine(){  
        console.error("Bicycles don't have engines");  
    }  
}
This structure violates LSP because we can not replace an object of the ‘Vehicle’ class with an object of the ‘Bicycle’ class as it will raise an error. We can solve this by replacing the ‘startEngine’ method with a generic ‘start’ method like this:
class Vehicle {  
    start() {  
        console.log('Starting the Vehicle')  
    }  
}  
  
class Bicycle extends Vehicle {  
    start(){  
        console.log("Pedaling the Bicycle");  
    }  
}
Instances of ‘Bicycle’ can be safely substituted for instances of ‘Vehicle’ without any unexpected behavior or errors.

Interface Segregation Principle (ISP)

A client should not be forced to depend on methods it does not use.
Segregation means keeping things separated. The Interface Segregation Principle is about separating the interfaces to prevent the creation of “fat” or “bloated” interfaces that include methods that are not required by all clients.
Let’s consider a scenario where we have an interface ‘Media Player’ which contains methods related to both Audio and Video controls:
interface MediaPlayer {  
    startVideo() : void // Video Play Logic  
    startAudio() : void // Audio Play Logic  
    stopVideo()  : void //Video Stop Logic  
    stopAudio()  : void //Audio Stop Logic  
}
In this case, any client that implements the ‘Media Player’ interface would be forced to implement all the methods, even if it doesn't need them. For example, an Audio Player would have to implement ‘startVideo’ and ‘stopVideo’ even if it does not need them.
To adhere to the ISP, we can segregate the interface into smaller, more focused interfaces:
interface AudioPlayer {  
    startAudio() : void  
    stopAudio()  : void  
}  
  
interface VideoPlayer {  
    startVideo() : void  
    stopVideo()  : void  
}
Clients are only dependent on the methods they require by making small and targeted interfaces. This guarantees loose coupling and improves code organization.

Dependency Inversion Principle (DIP)

High-level modules should not depend on low-level modules. Both should depend on abstractions.
The Dependency Inversion Principle is closely related to the Open/Closed Principle (OCP) we discussed earlier, as it encourages designing code that is easily extendable without modifying existing modules. Your high-level modules depend on abstractions rather than concrete implementations by following DIP. This reduces direct dependencies between modules. It also ensures decoupling, making the integration of new code smooth.
In his article (2000), Uncle Bob summarizes this principle as follows:
“If the OCP states the goal of OO architecture, the DIP states the primary mechanism”.
Let’s look at an example of how we can implement DIP in our code. Suppose we have two classes ‘LightBulb’ and Switch which are implemented like this:
class LightBulb {  
    turnOn(){  
        console.log('Bulb is on now')  
    }  
}  
  
class Switch {  
    lightbulb = new LightBulb()  
  
    operate(){  
        this.lightbulb.turnOn()  
    }  
}
You can see that the ‘Switch’ class is directly dependent on ‘LightBulb’ for its functionality which violates DIP.
We can avoid this by introducing an interface as an abstraction like this:
interface Switchable {  
    turnOn(): void  
}  
  
const lightBulb :Switchable ={  
    turnOn() {  
        console.log('Bulb on')  
    },  
}  
  
class Switch {  
    device: Switchable = lightBulb  
    operate(){  
        this.device.turnOn()  
    }  
}
The ‘Switch’ class does not depend on a concrete class; its implementation only depends on ‘device’, a generic interface ‘Switchable’ that fulfills DIP. This in turn makes the class easily extendable making it aligned with OCP. For example, I want to add another device called ‘fan’. What I need to do is this:
const fan: Switchable = {  
    turnOn() {  
        console.log('Fan on');  
    },  
};  
  
const switchForFan = new Switch();  
switchForFan.device = fan;  
switchForFan.operate();  // Output: "Fan on"

Conclusion

The SOLID principles are like a toolkit for writing better code. They help make your code easier to understand, maintain, and extend. As you continue your programming journey, keep these principles in mind, and you’ll find your code becoming more organized and adaptable. Remember, mastering these concepts takes time, so don’t be afraid to revisit them as you progress.
Happy coding!