Readable code requires less cognitive effort to maintain a mental model; hence, it is easier to read and maintain. A critical aspect of readability is the number of nested levels. Code is qualified as readable based on multiple criteria such as naming, consistency, formatting, and so forth. While programming, we need to maintain mental models (about overall code interactions and function implementations, for example). In general, the more nested levels a function requires, the more complex it is to read and understand.
The way we reduce the unnecessary nested code
Let’s see some different applications of this rule to optimize our code for readability:
When an if block returns, we should omit the else block in all cases. For example, we have checked if the string is empty and returned an error is empty.
We can make the above function optimized by removing the else function. In this example, we flipped the condition and were able to remove else condition
Writing readable code is an important challenge for every developer. Striving to reduce the number of nested blocks, aligning the happy path on the left, and returning as early as possible are concrete means to improve our code’s readability.
- 100 Go Mistakes and how to avoid them, Teiva Harsanyi, Manning Publications Co