Erring on the side of small
I’m going to cheat a little bit today. Most of the content of this post will be code, rather than my thoughts. But it’s a topic that’s been on my mind, so I figured, why not share it?
I’ve noticed amongst “junior” programmers a fairly consistent sign of inexperience: their functions tend to be longer than necessary, because they often try to do more than one thing.
For example — last week I was reviewing the code of one of my coworkers (sorry Jeff, I’m throwing you under the bus) and I came across the following function, which validates all the inputs of a form (represented by the inputs object, which maps the field names to their input values):
At a glance, I can spot a few nitpicky things, like the for loop that could be slightly simplified with a forEach, and a few nested if blocks that could be merged into a single conditional.
But the larger issue here is that this function is doing several things:
- Validating the presence of required fields
- Checking the validity of the provided email
- Checking the validity of the provided name
- Checking the validity of the provided date of birth
So let’s write some functions that do each of those, and then refactor and simplify a bit. (I also used the moment.js library to simplify the birth date validation function.) Here we go:
Now the code is much more readable, in my opinion. It will also be much easier to unit test, extend, and maintain.
I remember reading a rule about function length, something about making it a goal to keep the line count under some arbitrary number like 30 or 50. And I understand that being dogmatic about suggestions like that can be counterproductive. However…
I do believe that for beginners, striving to abide by this “rule” is great practice. In my experience, I’ve rarely seen junior developers abuse this advice. Nine times out of ten, however, I encounter the opposite: large, bloated functions that try to do too much.
So err on the side of small. Keep it simple.
As an afterthought, if we wanted to be a bit more “clever” with the above code, here’s another way I might refactor it using reduce and “higher-order functions” (so fancy!):
Happy coding 🤓
