How to write readable code? Here are some tips.
We spend more time on reading than on writing code. Readable code is essential. Here are my tips for writing readable code.
Naming is the first thing we can improve on writing readable code.
If we put proper names to variables, functions, classes, code will easy to be understood. Remember to choose the more self-descriptive names for variables or functions.
Naming is not easy and needs some practice.
There are only two hard things in Computer Science: cache invalidation and naming things.
—- Phil Karlton
Keep simple on every file or function. A class or function should do one thing or one similar thing only.
A function should not contain too many lines of code or arguments. Huge function makes things difficult to comprehend.
Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away.
– Antoine de Saint-Exupery
Reading code is similar to reading a book. If a book is organized well, we know the subject of each chapter, we can skip some sections if necessary.
Organize code well means each file contains and only contains related lines of code; each module or directory contains related source code files.
Write comments, but not too many …
Comments are helpful for understanding code, but too many comments will distract us.
It’s better to make comments not only restate the code.
So, in comments, we need to explain something outside of code. Add comments for the assumption, the desgins and limitations of the code.
For example, explain why you choose the used data structure.
Imagine others will read your code
Imagine you are not writing code, but explain your purpose to others.
Try to read the code after you finished it.
Read this book
This is an excellent book for anyone who wants to code professionally:
The Art of Readable Code (Theory in Practice)