(image caption): Just because you can, it doesn’t mean you should.
I’m reading through Sandi Metz’s Practical Object-Oriented Design in Ruby. It’s a fantastic book, and I highly recommend you pick up a copy, even if you don’t use Ruby.
In chapter 2, Sandi goes through how to apply the single responsibility principle (SRP). If you’re not fimiliar with the SRP, it’s a principle that states that a class should be responsible for only one thing.
Generally, if you can state what your class does in one sentence, without using any conjunctions (e.g. and, but, or), you’re following the SRP.
Towards the end of chapter 2 Sandi suggests that you should extend the SRP to each method on a class.
Here are some of the benefits of using SRP for each method (an excerpt from the book):
Expose previously hidden qualities
Refactoring a class so that all of its methods have a single responsibility has a clarifying effect on the class. Even if you do not intend to reorganize the methods into other classes today, having each of them serve a single purpose makes the set of things the class does more obvious.
Avoid the need for comments
How many times have you seen a comment that is out of date? Because comments are not executable, they are merely a form of decaying documentation. If a bit of code inside a method needs a comment, extract that bit into a separate method. The new method name serves the same purpose as did the old comment.
Small methods encourage coding behavor that is healhty for your application. Other programmers will reuse the methods instead of duplicating code. They will follow the pattern you have established and create small, reusuable methods in turn. This coding style propagates iteslf.
Are easy to move to another class
When you get more design information and decide to make changes, small methods are easy to move. You can rearrange behavior without doing a lot of method extraction and refactoring. Small methods lower the barriers to improving your design
As a personal experiment I’ve started applying the SRP to my methods.
The greatest benefit, that I’ve noticed, is that I don’t have to try and account for future changes - which are unknowable anyway - because my classes are comprised of tiny methods that are easy to change/remove/replace.
I highly recommend implementing Sandi’s ideas in your own code. I think you’ll see some immediate benefits.