Single Responsibility Principle

Single Responsibility Principle

A class should have only one reason to change. means

A class should have a single functionality.

  1. Each class and Module should focus on a single task at a time.
  2. Everything in a class should be related to a single Purpose.
  3. There can be many members in the class as long as they are related to a single responsibility.
  4. Classes have become smaller and cleaner.

Example

Assume we need to create an application that performs user registration and login.

Post it should be able to send an email to the user depending on the status of the user login or registration, and we should also be able to log any exception that can occur in this process as well.

So we will create an interface with all methods.

namespace Solid_principle
{
    internal interface IUser
    {
       bool Login(string username, string password);
       bool Registration(string username, string password, string Name);
       void LogError(string error);
       bool SendEmail(string emailcontent);
    }
}

It looks like ok to have these steps performed during the user registration process, but if we look closely, we can figure out that we do not need to have LogError() and SendEmail().

Part of the IUser because the user object should able to perform Login and registration only or one at a time.

We do not need to have LogError() and SendEmail() part of the IUser so we need to break it into separate interfaces.

namespace Solid_principle
{
    interface IUser
    {
       bool Login(string username, string password);
       bool Registration(string username, string password, string Name);
    }

    internal interface ILogger
    {
        void LogError(string error);
    }

    internal interface IEmail
    {
        bool SendEmail(string emailcontent);
    }
}

Having these three interfaces makes more sense as all interfaces are performing their own functionality.

  • IUser performs user-related (login and registration) responsibility.
  • ILogger performs error logging responsibility
  • IEmail performs mail-related responsibility.

Now we can see that we have segregated the single Responsibility Principle using multiple interfaces.


Similar Articles