Extract Till You Drop
Recently, I watched a video from Uncle Bob where he talked about writing clean code. One of the most striking suggestions that he made is that functions should be very small. He called it “Extract Till You Drop”. I will explore this and demonstrate how I used it in my most recent project.
According to Uncle Bob, a function should do one thing. Smaller functions should be extracted until nothing meaningful can be extracted from the function.
Let’s start off with this unextracted method from a project I co-authored, the Tournament Registration Project. It is a method used to reenter a poker tournament.
Rubymine says it’s too long and too complex. It mixes high level and low level ideas and might be hard to understand. I have since refactored this method using extract till you drop and it is much cleaner.
The extracted method does not give you as much detail, but that is a feature, not a bug. It takes the abstract concept of reentering a poker tournament and breaks it up into smaller methods with more detail and less abstraction. It follows the inverted pyramid concept from journalism(Wikipedia). I start with the headlines and give you the opportunity to leave early or stay for the details.
Another benefit of extracting all of these functions is that they will become easier to test. This is part of the divide and conquer mentality. It is easier to see where something fails when testing a small part versus the whole system.
One of the disadvantages of extracting all of these functions is that your codebase will have all of these functions. These small functions should be organized and have increasingly longer names as their scope becomes smaller and more specific.
There are many parts to writing clean code. I suggest you watch Uncle Bob’s presentation to see the rest of them. Extracting functions will make your code easier to read by separating the high level concepts from the low level concepts and you won’t feel like you are on an abstraction roller coaster.