5 Make code readable

 

This chapter covers

  • Techniques for making code self-explanatory
  • Ensuring that details within the code are clear to others
  • Using language features for the right reasons

Readability is inherently a subjective thing, and it’s therefore hard to put a solid definition on exactly what it means. The essence of readability is ensuring that engineers can quickly and accurately understand what some code does. Actually achieving this often requires being empathetic and trying to imagine how things might be confusing or open to misinterpretation when seen from someone else’s point of view.

This chapter should provide a solid grounding in some of the most common and effective techniques for making code more readable. It’s worth remembering, though, that each real-life scenario is different and has its own set of considerations, so using common sense and applying good judgment are both essential.

5.1 Use descriptive names

Names are needed to uniquely identify things, but they often also provide a brief summary of what the thing is. The word toaster uniquely identifies an appliance in your kitchen, but it also gives a massive hint as to what it does: it toasts things. If we, instead, insisted on referring to a toaster as “object A,” then it would be quite easy to forget what exactly “object A” is and what it does.

5.1.1 Nondescriptive names make code hard to read

5.1.2 Comments are a poor substitute for descriptive names

5.1.3 Solution: Make names descriptive

5.2 Use comments appropriately

5.2.1 Redundant comments can be harmful

5.2.2 Comments are a poor substitute for readable code

5.2.3 Comments can be great for explaining why code exists

5.2.4 Comments can provide useful high-level summaries

5.3 Don’t fixate on number of lines of code

5.3.1 Avoid succinct but unreadable code

5.3.2 Solution: Make code readable, even if it requires more lines

5.4 Stick to a consistent coding style

5.4.1 An inconsistent coding style can cause confusion