Quick Primer: SOLID

· 4 min read


Thought it might be a bit of fun to jot down a quick primer for SOLID principles - helpful if you have an exam and need to crunch.

What is SOLID?

Single Responsibility Principle (SRP)

Open-Closed Principle (OCP)

Liskov Substitution Principle (LSP)

Interface Segregation Principle (ISP)

Dependency Inversion Principle (DIP)

Benefits of SOLID Principles

Challenges

Summary

SOLID principles provide a foundation for designing clean, maintainable, and flexible software in object-oriented programming.

They guide developers in creating code that is less error-prone and easier to extend and modify.

Code Example

Single Responsibility Principle

The Single Responsibility Principle in object-oriented programming states that a class should have only one reason to change. In other words, a class should have a single, well-defined responsibility. Here’s an example in C# that demonstrates a violation of the Single Responsibility Principle:

using System;

// Violates the Single Responsibility Principle
public class User
{
    public string Name { get; set; }
    public void SaveToDatabase()
    {
        // Code for saving the user to a database
        Console.WriteLine("User saved to the database.");
    }
    public void SendEmail()
    {
        // Code for sending a welcome email to the user
        Console.WriteLine("Welcome email sent to the user.");
    }
}

In this example, the User class has two responsibilities: saving the user to a database and sending a welcome email. This violates the SRP because a change in one of these responsibilities may affect the other. For instance, if you need to change the way users are saved to the database, you’d have to modify the User class, potentially impacting the email-sending functionality.

To adhere to the SRP, you should split these responsibilities into separate classes:

using System;

// Following the Single Responsibility Principle
public class User
{
    public string Name { get; set; }
}

public class UserRepository
{
    public void SaveToDatabase(User user)
    {
        // Code for saving the user to a database
        Console.WriteLine("User saved to the database.");
    }
}

public class EmailService
{
    public void SendWelcomeEmail(User user)
    {
        // Code for sending a welcome email to the user
        Console.WriteLine("Welcome email sent to the user.");
    }
}

In this revised code, we have three separate classes, each with a single responsibility. The User class only represents user data, the UserRepository class handles database operations, and the EmailService class takes care of sending emails. This adheres to the Single Responsibility Principle, making the code more maintainable and less prone to unintended side effects when changes are required in one part of the system.