A pretty straight forward principle but at the same time difficult to detect its violations.
A few definitions...
1. Each object is interested in doing its job, and only its job.
2. Every object in your system should have a single responsibility and all the object's services should be focussed on carrying out that responsibility.
3. A class should have only one reason to change.
4. Cohesion is another name for SRP. If you are writing highly cohesive software, then that means you are correctly applying SRP.
How to detect SRP violations ?
1. Objects should do what their names indicate.
2. Each object should represent a single concept.
3. Unused properties are a dead giveaway. If you have an object that is being used with null prperties most often, then you probably have an object doing more than one job. Why is the property there in the first place ?
Would suggest reading through the article at objectmentor.com
A some what related principle is DRY (Don't repeat yourself). It says 'Avoid duplicate code by abstracting out things that are common and placing those things in a single location.' Duplicate code would always lead to maintenance nightmares !!!
DRY is about having each piece of information and behavior in your system in a single place. It is also called as Say it once and Only once.
Q. How does removing code duplication help in improving cohesion ?
One of the best ways to improve cohesion in your system is to eliminate duplication wherever you spot it. It's probably best if you assume that you don't know exactly how your system is going to change in the future, but you can improve your code's ability to accept change by maintaining good cohesion and coupling in class structures. One of the best ways to improve the cohesion quality of your codebase is to simply pull out duplication into separate classes that can be shared across the codebase.
Saturday, June 14, 2008
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment