Writing clear code is extremely important when working in large teams, solving challenging problems and developing sophisticated software.
A line of code that you write today could be read hundreds of times over the next few months. Your team members may check your code, they will need to interact with your code, and you will reread your code when fixing bugs. Thus, there is a danger that cutting corners for short term gains will waste effort in the long term.
For example, consider a method to add a customer’s mobile phone number to an order. You could name the method addMobPhNo
to save a few keystrokes. However, using a longer name such as addMobilePhoneNumber
will save you and your team members much more time when you have to read and debug code.
Everyone knows that debugging is twice as hard as writing a program in the first place. So if you’re as clever as you can be when you write it, how will you ever debug it?
The Elements of Programming Style, Second Edition (Chapter 2)
I believe that writing clear code is an art. It is an art form that everybody can practice. The art of clear code is about discovering simplicity, even in complex problems.
In this chapter, I will explore simplicity as well as some of the details of the JavaScript programming language.
The JavaScript language has a poor reputation with some developers because of its complex and quirky design. An understanding of these quirks makes it possible to avoid writing code that is ‘too clever’. Instead, an in-depth understanding of the language will empower you to write clear code that avoids the unnecessary complexity of JavaScript.
What does “simplicity” mean?
We might take guidance from the sciences: Ockham’s razor is the principle that a short explanation more likely to be correct than a long explanation. This idea dates back at least two millennia to Aristotle but underpins modern scientific inquiry and even cutting edge machine learning.
In practice, a simple explanation of a problem is likely to have the following attributes:
-
Uses a small number of rules
-
Each rule is easy to understand
-
No (or very few) exceptions to the rules
This idea has application to both code and programming languages. Simple code should be small, short and have few branches or specialized logic. Simple programming languages should operate based on simple principles with few exceptional cases.