Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

principle
solid
responsibility
class

What is the single responsibility principle?

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.
    }
}

RELATED TAGS

principle
solid
responsibility
class
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring