Table of Contents
Readable code means that the code has a good balance of being easy to understand in terms of what it is doing, and of being concise.
Why does readable code matter?
When code is easy to read, it’s easy to debug, maintain, and extend.
It’s not uncommon for a developer to write code at the beginning of a system development process, and then realize a year later that they don’t understand their own code and thus will need to re-teach themselves their own system.
If someone else wrote the code, and it’s unreadable, it’s not uncommon for developers to re-write the entire system as a result, which is an inefficient way to build software.
Structure Your Code
Classes and methods should be consistent, easy to understand, and easy to navigate.
Simplify Your Code
Aim to make your code elegant—simple to read, orderly, and easy to understand. Don’t try to over-complicate things with elaborate tricks. Keep your classes a reasonable size and most of your functions short.
Stick To The Style Guide
If the repository you’re working in has standard code formatting and style guidelines, use them. Stick to the maximum length per line used in other code in that repository, etc.
Names Should Be Self-Explanatory
A big aspect of making your code easy to read lies in the names you choose. The names of your functions should clearly describe their purpose. Name your variables, function, and methods in a way that describes what they do or what they are.
For example, if your variable gets something, consider including “get” in its name. If you can’t name the method or function without using many words, the function may be too complicated. Consider going back and breaking complicated functions into smaller functions to simplify.
Ensure Blocks Are Self-Contained
The single responsibility principle means that every building block does only one thing. All building blocks, including methods, variables, and classes, follow this rule so it’s easy for the person reading the code to understand their responsibility.
When your code follows this principle, it’s easier to maintain and more scalable. When concerns are separated, you can focus on what features you actually want to work on rather than having to navigate interconnected lines of code.
Ensure Comments Are Minimal
Comments shouldn’t tell us what we already know. They should tell us why things are happening. You shouldn’t have to write more than 1-2 lines in a comment to explain what the code is doing. If you have to, consider rewriting the code until it is more readable. If the code is obvious, avoid comments altogether. The code should be able to speak for itself in many cases.