Monday, January 5, 2009

Essential Software Concepts: The Single Responsibility Principle (SRP)

The Single Responsibility Principle defines that a class should have only one responsibility, also defined as only one reason to change. (Defined by Uncle Bob in Agile Principles, Patterns, and Practices in C#. A book well worth reading.)


In other words, it should only be responsible for one thing. Do only one thing. Handle only one area. Potato, Potato. 


The principle is really simple in concept, yet it can be difficult to follow at times. It is an important principle to follow because it will make your classes more robust to change. Coupled responsibilities can lead to code that breaks more easily, changes that are more expensive to implement, tests that are harder to make concrete, less readable code and more code to step through when debugging.


That doesn't mean you _always_ need to follow it. The cost of separating things can be higher than the cost of holding them together. If you expect no change, then stay with that. Possibly separate the concepts by creating separate interfaces. That way the implementation stays coupled, but at least the rest of the system is not coupled to the mess.

No comments: