Friday, July 18, 2008

The Single Responsibility Principle (SRP)

Every object in your system should have a single responsibility, and all the object's services should be focused on carrying out that single responsibility.


Cohesion is another name for the SRP. The SRP will often make you classes bigger. Since you're not spreading out functionality over a lot of classes, you're putting more things into a class.

This is the reason why many people separate their applications into layers, for example, the data access layer, the business layer and the presentation layer. Hopefully a change in one layer won't cause a ripple effect of changes in other layers, or at least, keep the impact to a minimum. A popular example that "violates" this principle is placing persistence logic in your business classes. By doing so, you have 2 reasons for a business class to change. First, when you need to change the persistence logic, and second, when you need to change the business rules.

Most of the time, you can spot classes that aren't using the SRP with a simple test:

For example,

Read each line below, if what you read does not make sense, you're probably violating the SRP with that method. That method might belong to a different class.

Once you've done an analysis, you can take all the methods that don't make sene on a class, and move those methods to classes that do make sense for that particular responsibility.

When a method takes parameters, like wash(Automobile) on the CarWash class. You would write "The CarWash washes [an] automobile", which makes sense.

No comments:

Post a Comment