Functions – Smaller Is Better

This will be the first post covering the topic of functions. So far, this has probably been the approach to clean code that has been the hardest for me to wrap my head around. Not because it’s difficult, but because it is opposite to the way that I have been writing functions for my entire coding career. In this post we will start to build the argument for small functions.

How most functions are written

Think about the last time you sat down in front of your computer to write a function. Hopefully, you dedicated some time beforehand to think about it, until you had a pretty good idea of how to write it. Maybe you felt brave that day and decided to just start coding and let the steps show themselves to you. In any case, you opened your text editor or IDE and started typing.  After some time you sit back and marvel at your work. The code seems to be clear and efficient, even though the logic was somewhat complex, and you did it in only 200 lines of code! You even commented the key parts of the code, in case someone has to modify it in the future. You consider it a job well done and move on to the next task at hand.

Make your functions small! Smaller Than That!

Why would you want to make the function in the previous example smaller? How could you even make it smaller if you wanted to? One answer to the first question would be to make the code even easier to understand. The answer to the second question is to extract the different steps taken inside the function to separate functions until you can’t extract anymore. In his video series, uncle Bob refers to this as “extract ’til you drop”. He even goes as far as to say that functions should be no longer than 6 lines of code. The first time I saw the video, I thought he was crazy for saying that, but he actually managed to make a valid argument for his point of view. While I can´t say that all the functions I write now adhere to his guideline, they have certainly gotten a lot smaller.

How can we make the functions smaller? How do we know which parts to extract into which functions? Future posts will help you learn how to do this, but it boils down to make sure that each function does one thing.

Do One Thing

Functions should do one thing. They Should do it well. They should do it only.

Writing functions that do one thing is the key to having small functions. The definition of doing one thing can sometimes be tricky.  If you were writing a shopping cart application, someone could argue that placing the customer’s order is one thing. Someone else would say that it’s not one thing because placing an order actually involves updating the customer’s records, reducing the inventory, notifying the shipping company that there’s a package, etc. So who’s right? Actually, they both are, only that they are right for different abstraction levels.

We will continue this discussion in the next post, which addresses abstraction levels. Stay tuned!

Leave a Reply