Writing Code Is Writing

Note: This is my opinion. If you have thoughts or concerns, that's fine - feel free to message me.

When writing code, it’s easy to fall into that trap of thinking that you’re writing for the computer. You’re not. You’re writing for other engineers... whether it be your coworkers, the open source community, or yourself in six months. Making sure your code is human-readable is just as important as making sure it works.

How do you make code human-readable? Think about the intended message of each line. For instance, I once had a hard rule to never type value === true for boolean variables because it was technically redundant. For example, let’s look at the following snippet:


if (value) console.log(value);
        

This is quite readable to me. I can easily read this as, “if there’s a value, log the value to the console.”

Now the next example:


Object.values(form.checkboxes).every((checkbox) => checkbox);
        

Is it immediately obvious what this code is doing? I don’t think so. It’s not difficult code, but you do have to do an extra run around the mental event loop for your brain to process it. “This is checking if every checkbox in the form is…?”

The change that would make this code clearer to me would be the following:


Object.values(form.checkboxes)
  .every((checkbox) => checkbox === true);
        

The === true here is completely unnecessary when it comes to the functionality of the code, but does wonders for the legibility of the code. “Ah! This is checking if every checkbox in the form is true.”

Notice what I’ve been doing in all of the examples above? Reading your code back to yourself using natural language is a great way to gauge code clarity.

You aren’t a robot and your code shouldn’t appear to be written by one. Don’t simplify your code without thinking. What you choose to include or exclude should depend a great deal on what makes it easier to read.

Duck