Introduction

Welcome to the final lesson of the "Applying Clean Code Principles" course! Throughout this course, we've covered vital principles such as DRY (Don't Repeat Yourself), KISS (Keep It Simple, Stupid), and the Law of Demeter, all of which are foundational to writing clean and efficient code. In this culminating lesson, we'll explore the SOLID Principles, a set of design principles introduced by Robert C. Martin, commonly known as "Uncle Bob." Understanding SOLID is crucial for creating software that is flexible, scalable, and easy to maintain. Let's dive in and explore these principles together.

SOLID Principles at a Glance

To start off, here's a quick overview of the SOLID Principles and their purposes:

  • Single Responsibility Principle (SRP): Each class or module should only have one reason to change, meaning it should have only one job or responsibility.
  • Open/Closed Principle (OCP): Software entities should be open for extension but closed for modification.
  • Liskov Substitution Principle (LSP): Objects of a superclass should be replaceable with objects of its subclasses without affecting the correctness of the program.
  • Interface Segregation Principle (ISP): No client should be forced to depend on methods it does not use.
  • Dependency Inversion Principle (DIP): High-level modules should not depend on low-level modules. Both should depend on abstractions.

These principles are guidelines that help programmers write code that is easier to understand and more flexible to change, leading to cleaner and more maintainable codebases. Let's explore each principle in detail.

Single Responsibility Principle

The Single Responsibility Principle states that each class should have only one reason to change, meaning it should only have one job or responsibility. This helps in reducing the complexity and enhancing the readability and maintainability of the code. Consider the following:

public class User
{
    public void PrintUserInfo()
    {
        // Print user information
    }

    public void StoreUserData()
    {
        // Store user data in the database
    }
}

In the above code, the User class has two responsibilities: printing user information and storing user data. This violates the Single Responsibility Principle by taking on more than one responsibility. Let's refactor:

public class User
{
    // User-related attributes and methods
}

public class UserPrinter
{
    public void PrintUserInfo(User user)
    {
        // Print user information
    }
}

public class UserDataStore
{
    public void StoreUserData(User user)
    {
        // Store user data in the database
    }
}

In the refactored code, we have three classes, each handling a specific responsibility. This makes the code cleaner and easier to manage.

Open/Closed Principle

The Open/Closed Principle advises that software entities should be open for extension but closed for modification. This allows for enhancing and extending functionalities without altering existing code, reducing errors and ensuring stable systems. Consider this example:

public class Rectangle
{
    public double Width { get; set; }
    public double Height { get; set; }
}

public class AreaCalculator
{
    public double CalculateRectangleArea(Rectangle rectangle)
    {
        return rectangle.Width * rectangle.Height;
    }
}

In this setup, if we want to add a new shape like Circle, we need to modify the AreaCalculator class, violating the Open/Closed Principle. Here is an improved version using polymorphism:

public interface Shape
{
    double CalculateArea();
}

public class Rectangle : Shape
{
    public double Width { get; }
    public double Height { get; }

    public Rectangle(double width, double height)
    {
        Width = width;
        Height = height;
    }

    public double CalculateArea()
    {
        return Width * Height;
    }
}

public class Circle : Shape
{
    public double Radius { get; }

    public Circle(double radius)
    {
        Radius = radius;
    }

    public double CalculateArea()
    {
        return Math.PI * Radius * Radius;
    }
}

public class AreaCalculator
{
    public double CalculateArea(Shape shape)
    {
        return shape.CalculateArea();
    }
}

Now, new shapes can be added without altering AreaCalculator. This setup adheres to the Open/Closed Principle by leaving the original code unchanged when extending functionalities.

Liskov Substitution Principle

The Liskov Substitution Principle ensures that objects of a subclass should be able to replace objects of a superclass without altering the functionality or causing any errors in the program.

public class Bird
{
    public virtual void Fly()
    {
        Console.WriteLine("Flying");
    }
}

public class Ostrich : Bird
{
    public override void Fly()
    {
        throw new NotSupportedException("Ostrich can't fly");
    }
}

Here, substituting an instance of Bird with Ostrich causes an issue because Ostrich cannot fly, leading to an exception. Let's refactor:

public class Bird
{
    // Common behaviors for all birds
}

public class FlyingBird : Bird
{
    public virtual void Fly()
    {
        Console.WriteLine("Flying");
    }
}

public class Ostrich : Bird
{
    // Specific behaviors for ostriches
}

By introducing FlyingBird and having only birds that can actually fly inherit from it, we can substitute Bird with Ostrich without errors, adhering to Liskov’s Substitution Principle.

Interface Segregation Principle

The Interface Segregation Principle states that no client should be forced to depend on methods it does not use. Interfaces should be split into smaller, more specific entities so that clients only implement the methods they need:

public interface Worker
{
    void Work();
    void Eat();
}

public class Robot : Worker
{
    public void Work()
    {
        // Robot work functions
    }

    public void Eat()
    {
        // Robots don't eat, but must implement this method
    }
}

Robot being forced to implement Eat() violates the Interface Segregation Principle. Here's the refactored version:

public interface Workable
{
    void Work();
}

public interface IEatable
{
    void Eat();
}

public class Robot : Workable
{
    public void Work()
    {
        // Robot work functions
    }
}

Now, Robot only implements the Workable interface, adhering to the Interface Segregation Principle.

Dependency Inversion Principle

The Dependency Inversion Principle dictates that high-level modules should not depend on low-level modules, but both should depend on abstractions. Here's an example:

public class LightBulb
{
    public void TurnOn()
    {
        Console.WriteLine("LightBulb turned on");
    }

    public void TurnOff()
    {
        Console.WriteLine("LightBulb turned off");
    }
}

public class Switch
{
    private LightBulb _lightBulb;

    public Switch()
    {
        _lightBulb = new LightBulb();
    }

    public void Operate()
    {
        // Operate on the light bulb
    }
}

Here, Switch directly depends on LightBulb, making it difficult to extend the system with new devices without modifying Switch. Every time a new device type is introduced, the Switch class would need modification, leading to tight coupling.

To adhere to the Dependency Inversion Principle, we introduce an abstraction:

// Abstraction: Interface representing switchable devices
public interface ISwitchable
{
    void TurnOn();
    void TurnOff();
}

// Low-level module: Implementation of the ISwitchable interface
public class LightBulb : ISwitchable
{
    public void TurnOn()
    {
        Console.WriteLine("LightBulb turned on");
    }

    public void TurnOff()
    {
        Console.WriteLine("LightBulb turned off");
    }
}

// High-level module: Uses abstraction (ISwitchable) to operate on switchable devices
public class Switch
{
    private ISwitchable _client;

    public Switch(ISwitchable client)
    {
        _client = client;
    }

    public void Operate()
    {
        // Operate on the switchable client
    }
}

Now Switch uses the ISwitchable interface, which can be implemented by any switchable device. This setup allows the Switch class to remain unchanged when introducing new devices, thus following the Dependency Inversion Principle by depending on an abstraction and reducing the system's rigidity.

Review and Next Steps

In this lesson, we delved into the SOLID Principles — Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion. These principles guide developers to create code that is maintainable, scalable, and easy to extend or modify. As you prepare for the upcoming practice exercises, remember that applying these principles in real-world scenarios will significantly enhance your coding skills and codebase quality. Good luck, and happy coding! 🎓

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal