THERE SHOULD NEVER BE MORE THAN ONE REASON FOR A
CLASS TO CHANGE.
It is important to separate two responsibilities into two separate classes.Because each responsibility is an axis of change. When the requirements change, that change will be manifest through a change in responsibility amongst the classes. If a class assumes more than one responsibility, then there will be more than one reason for it to change.If a class has more then one responsibility, then the responsibilities become coupled.Changes to one responsibility may impair or inhibit the class’ ability to meet the others.This kind of coupling leads to fragile designs that break in unexpected ways when changed.
E.g. If we define a Rectangle class with two methods. One draws the rectangle on the screen, the other computes the area of the rectangle. Two different applications use the Rectangle class. One application does computational geometry. It uses Rectangle to help it with the mathematics of geometric shapes.It never draws the rectangle on the screen. The other application is graphical in nature. It may also do some computational geometry, but it definitely draws the rectangle on the screen.
This design violates the SRP. The Rectangle class has two responsibilities. The first responsibility is to provide a mathematical model of the geometry of a rectangle. The second responsibility is to render the rectangle on a graphical user interface.
The violation of SRP causes several nasty problems. Firstly, we must include the GUI
in the computational geometry application. In a Java application, the .class files for the GUI have to be deployed to the target platform. Secondly, if a change to the GraphicalApplication causes the Rectangle to
change for some reason, that change may force us to rebuild, retest, and redeploy the ComputationalGeometryApplication. If we forget to do this, that application may break in unpredictable ways.
No comments:
Post a Comment