Sunday, April 27, 2008

Single Responsibility Principle (SRP)

Principle: A class (object) should have one and only one, reason to change

SRP says, a class (object) should emit a single behavior (collection of methods resulting in that one behavior). Any changes to the object's behavior should only be the reason to make changes to its corresponding class. Adhering to SRP should result in modular, flexible and cohesive interfaces.

Here is an example that violates SRP

class Payroll {
public:
void ComputePaySlip( const std::string & emp_id );
void ShowPaySlip( const std::string & emp_id );

...
};

There are two tasks in Payroll class , pay computation and pay slip presentation. Potentially these two jobs can be separated out each going into its own class.

The computation part calculates the monthly pay based on number of working hours, special incentives if any, any deductions and tax to withhold etc. If the taxation rules changes, the behavior of Payroll needs to be modified (for a valid reason) but it might unknowingly disrupt the functionality (behavior) of the pay slip presentation part as both were sharing the same object data.

In similar manner, any change in requirements to modify the presentation logic might affect the pay computation part due to the implicit dependency (being part of the same object).

It might be a good idea to break the class into two as the current class seems to emit two potentially different behaviors. Decoupling the behaviors helps handling behavior change without worrying about potentially damaging the other (doesn't it sounds better dependency management?).

SRP might be very hard to implement, it requires good ability in judging what should be considered a single behavior (demarcating or separating behaviors is a complex job :-), but results would be plenty ).

References

SRP (objectmentor)
Advanced Principles of OO Class Design - PPT
Cohesion - SRP
SRP (wikipedia)
SRP (DDJ)


Previous Topic:

Open Closed Principle

No comments: