What is the single responsibility principle?

The single responsibility principle is the first of five SOLID principles. The principle details that a module should have only one responsibility. This also means that the module should only change in the future for one specific reason.

svg viewer

Example

Suppose that there is a Shape class that draws a shape and then fills it in with color:

class Shape{
    private int size;

    public Shape(int i){
        size = i;
    }
    public void draw(){
        // Code to draw the shape.
    }
    public void colour(){
        // Code to fill the shape with colour.
    }
}

This class can be changed in the future for two main reasons:

  • We want to change the figure of the shape.
  • We want to change how the shape is colorized.

This means that the single responsibility principle is being violated because the class can be changed for more than one reason.

Conforming to the single responsibility principle would result in two separate classes: one for drawing and another for coloring.

class DrawShape{
    public static void draw1(){
        // Draw the shape in a particular way.
    }
    public static void draw2(){
        // Draw in a different way.
    }
}

class FillShape{
    public static void colour1(){
        // Fill the shape with a colour.
    }
    public static void colour2(){
        // Fill with a different colour.
    }
}

Copyright ©2024 Educative, Inc. All rights reserved