Reputation: 1633
From Wikipedia:
Martin defines a responsibility as a reason to change, and concludes that a class or module should have one, and only one, reason to change.
However, every time you see an object-oriented analogy, they refer to cats and dogs, and how they have attributes and methods like so:
class Dog extends Animal{
public breed;
public dogYears;
public function bark();
public function move();
public function sleep();
etc, etc...
}
I find a better way to implement bark, so I do that. I see that the dog doesn't move properly, so I fix that. Etc etc. There are more than one reason to change the class.
So, why is this analogy always used? What would be a better way to adhere to the SRP?
Upvotes: 1
Views: 74
Reputation: 68680
Don't take it so literally.
In your example, Dog is responsible for performing real life "dog actions", such as barking, moving and sleeping. You can see this as one responsability. The SRP states that Dog
should not be responsible for perming any non-dog actions, such as logging his movements.
This prevents you from having to change the Dog
class if you decide to change the logging mechanism - because performing "dog actions" and logging are two completely different responsibilities.
Upvotes: 4