The single responsibility principle (SRP) is one of the foundations of good object oriented design, taking pride of place as the “S” in SOLID. It states that a class should have a single responsibility which should be encapsulated by that class and that the class’s interface (i.e. public methods) should be closely aligned with that responsibility. Let’s look at an example.
class Dog def bark # woof end def fetch # woof woof! end def chew_on_the_furniture # om nom nom end end
Our (albeit contrived) Dog class adheres to the single responsibility principle as all its operations relate directly to Dog stuff. Good dog! Now let’s give our dog one more ability.
class Dog def bark # woof end def fetch # woof woof! end def chew_on_the_furniture # om nom nom end def build_kennel # umm... end end
Now our Dog can build its own kennel, great! Or is it? Well, no. There’s two problems with this. One is that, dogs don’t have thumbs and as such cannot use hand tools and as we all know a dog with thumbs is an abomination. The second is that it has two concerns, dog stuff and carpentry. There it is, the “and”. You can easily spot that something violates the single responsibility principle whenever you find yourself saying “and” about class functionality.
But, why do we care? Well, adhering to the single responsibility principle helps us keep out code more loosely coupled, conceptually clean and here’s the big one, IT MAKES CHANGE EASIER. Change is what’s hard about building software (that and naming things) and the single responsibility principle helps us make sure that when we do need to change something, it’s nicely encapsulated, decoupled and much less likely to break other stuff.
TLDR; You should follow the SRP because dogs don’t have thumbs.