Method Length and Extract Till You Drop

As a typical nerd (and a DZone Zone Leader), I tend to read a lot of blog posts and comments about programming. One thing that keeps amazing me how long people’s functions tend to be and how many people are convinced this is the right way to code. In reality, a readable function should rarely exceed 5 lines of code.

Take a short look at this function:

How readable is that piece of code? Are you able to tell what it does just by taking a quick look at it? Two little extractions should make things clearer:

Much better. Now, the three functions are fairly readable and it should be easier to reason about what’s happening in there. But that’s still not good enough. Our show() method has mixed levels of abstraction and there’s still a loop inside an if statement. To deal with the first problem, we can simply extract two methods:

Now, how readable is that? It’s trivial, but that’s a good thing. We want our code to be trivial. Now to the second problem. Guess what we’ll do. That’s right, extract again!

Do you see how much clearer the code becomes? That’s exactly the point. When you extract, things become more digestible and it’s easier to preserve proper levels of abstraction. The fun part of it? You can extract all the time! Extract till you drop!

And in the meantime, your functions will become smaller and smaller. Usually less than 6 lines of code long. This is approximately the size at which code becomes pleasantly trivial. Therefore, beware of functions longer than that and continuously seek possibilities to extract further. The readers of your code will thank you.

About the Author Grzegorz Ziemoński

King of Tidy Java, nerd that thinks about producing perfect software all the time and proud owner of 2 cats.

follow me on: