The Art of Writing Clean Code
Principles and practices for writing code that is easy to read, understand, and maintain.
Clean code is not just about making code work—it's about making code that others (including your future self) can easily understand, modify, and extend. It's an investment that pays dividends throughout the lifetime of a project.
Meaningful Names
The name of a variable, function, or class should tell you why it exists, what it does, and how it's used. If a name requires a comment to explain it, the name doesn't reveal its intent.
- Use intention-revealing names
- Avoid disinformation and mental mapping
- Make meaningful distinctions
- Use pronounceable and searchable names
Functions Should Do One Thing
A function should do one thing, do it well, and do it only. This principle leads to smaller functions that are easier to test, understand, and reuse. If you can extract another function from it with a name that is not merely a restatement of its implementation, you're doing too much.
The first rule of functions is that they should be small. The second rule of functions is that they should be smaller than that.
Comments Are Often Failures
The proper use of comments is to compensate for our failure to express ourselves in code. When you find yourself writing a comment, think if there's a way to turn the code itself into documentation. Well-written code rarely needs comments.
When Comments Are Necessary
Sometimes comments are necessary: legal comments, informative comments about intent, clarification of obscure arguments, or warnings of consequences. But if you need them, make sure they add value.
The Boy Scout Rule
Leave the code better than you found it. Every time you touch code, make a small improvement. Over time, these small improvements compound into significant quality gains.