The Single Responsibility Principle (SRP) is a key concept in software design that states that a function should only do one thing. This means that a function should have a single, well-defined purpose and should not be responsible for multiple tasks or concerns.
A simple example of this principle in action is a function that calculates the area of a rectangle. This function should only be responsible for the area calculation and not for any other tasks, such as printing the result or validating input. By keeping the function focused on a single responsibility, we make it easier to understand and maintain. Other functions should be responsible for different tasks, such as displaying the result or handling user input.
void calculateTriangleArea() {
double side1, side2, side3;
cout << "Enter the length of the first side of the triangle: ";
cin >> side1;
cout << side1 << endl; // echo the input
cout << "Enter the length of the second side of the triangle: ";
cin >> side2;
cout << side2 << endl; // echo the input
cout << "Enter the length of the third side of the triangle: ";
cin >> side3;
cout << side3 << endl; // echo the input
double s = (side1 + side2 + side3) / 2; // Semi-perimeter
double area = sqrt(s * (s - side1) * (s - side2) * (s - side3)); // Heron's formula
cout << format("The area of the triangle to one decimal is: {:.1f}", area) << endl;
}
int main() {
calculateTriangleArea();
}
This makes the function less flexible. What if we want to calculate the area of a triangle and then use that value to do more calculations? We canβt do that easily because the result is just sent to cout. There is no way for other code to access the value produced inside that function.
Getting user input and printing out results are distinct tasks from working with data. They should generally not be a part of functions that perform calculations or data processing.
It also makes it harder to test each individual part of the function. There is no way to test that the area calculation is correct without also testing the input and output. If we want to change how the area is calculated, we have to change the entire function, which can introduce bugs in the other parts of the function. In this example, there is an extra complicationβit is much more challenging to build unit tests that work with cin and cout than it is to write ones that check the values returned from functions.
Now, if we want to use the results of calculateTriangleArea for further calculations, we can easily do so because it returns a value. For example, we could use it to help build a program that compares two triangles in order to decide if one is larger than the other.