A class should have one and only one reason to change
This principle states that a module, class or function should have one, and only one, reason to change. This means that a class or function should have one, and only one, responsibility. The principle is intended to make code more maintainable and to prevent code from becoming too complex.
In practice, this means that a class or function should have a single, well-defined purpose, and all its methods and properties should be related to that purpose. One way to understand this principle well is to think that different things must change for different reasons.
For example, consider the following code which calculates the area of a rectangle and has a method to log it:
}
}
}
}
This violates the principle of single responsibility, as this class has the responsibility of calculating the area and logging it.
One way to fix this would be to separate this function from its class and create a class of its own, and use that to log the area of the rectangle.
}
}
}
}
}
RectangleLogger.
By doing this separation, now each class has a single responsibility.