In books such as Eloquent Ruby short focused methods are preferred over methods that do too much.
Writing code in this fashion makes our classes easier to read. But what happens when we stumble upon a method or series of methods where their body is just as clear as their containing method’s signature?
In the book I’ve been reviewing, Refactoring Ruby Edition, we are instructed to get rid of the containing method. The authors reasoning is that although indirection can be helpful, needless indirection can have the opposite effect.
When to Use Inline Method
If you are used to reading other peoples code (or your own) and find that you are still becoming lost in all the method delegation to other methods, you may find yourself in a position to streamline some of this with the goal of clarity in mind.
When NOT to Use Inline Method
If you check the first comment below, Thiago makes some good points about when not to use Inline Method. I wanted to draw your attention to his comment as it serves well to remind us that if we are making a lot of calls on the wrapper method, we shouldn’t feel like we have to be so driven as to make this refactor change when it actually may not serve us due to the points he made, have a look at what he says below.
How to Use Inline Method
Here are the steps to perform an Inline Method refactor.
- Make sure any subclasses don’t override the method in question. Since our intention is to remove the container method altogether, this obviously won’t work
- Find all calls to the method in question and replace each call with the body of the method
- Test, to ensure that the expected functionality is still performing as expected
- Remove the method definition
Inline Method Example
When a method’s body is just as clear as it’s name, we find ourselves with a case for using Inline Method.
Here’s a quick example:
Since I am of the opinion, based upon the above gist example, that the containing method does little to add to clarity. I would want to just use the method’s body and get rid of the unnecessary hiding of the method and constant that-in my opinion-already does a pretty good job of being descriptive.
My interpretation from reading this refactoring pattern is this. Delegation is a good thing, and offers more than a couple benefits. But as with anything, if done too much, can have an effect that can be dissimilar to an improvement.
When our container method is adding to our confusion more than helping us to comprehend at a glance what is happening, its ok to remove this container method and leave it’s former code body as all the description that another reader, or ourselves, will need to assess whats going on.
If you know of any other cases in which Inline Method could be considered as a good refactoring pattern option, feel free to leave a comment.