This is one of the greatest lessons I learned on the topic of writing clean code from my mentor at my internship at Bloomberg during the summer of 2019. To write better code, in particular, writing better functions we must think about the: intention of the function we are writing.
This lesson is best illustrated with an example. Let’s say we are given a linked list as an input:
1->2->3->4->5. Our desired output is
1->5->2->4->3. A messy (but optimized) solution may be:
But as you can see, this code is awful… The
interleave_list() function is horribly bloated. Just by the name
interleave_list you’d expect this function to interleave items within an inputted list. However this function is doing more than that. The function is also
- computing the middle item of the list
- reversing the latter half of the list.
While these steps are certainly necessary and the code is producing the correct solution, it is wrong to implement these computations in
interleave_list() because this function should NOT care about how these other computations are accomplished.
Ask yourself these questions:
interleave_list()be the one computing the middle item of the list? No. This function should only be concerned about interleaving the items of the list
interleave_list()be the one reversing the latter half of the list? No, for the same reason as before
The intention of
interleave_list() is purely to interleave items of the list.
By exporting these computations to helper functions, we not only make these computations more modular, but the implementation of
interleave_list() is more concise, and readable which is invaluable when it comes to debugging.
Here is the solution refactored with improved code quality:
I hope that by thinking in terms of function intention you’ll be able to develop intuition on writing cleaner code 😃