There is no official top 10 list of clean code principles. “Clean code” usually refers to the practices in Robert C. Martin’s book Clean Code: A Handbook of Agile Software Craftsmanship (2008) and similar writing. Different authors, teachers and teams pick different sets of rules, so the list below is a commonly cited selection, not a standard.
Ten widely cited principles
- Use meaningful names. A variable, function or class name should say what it holds or does. A name like
dtells a reader little, whileelapsedDaysexplains itself. - Keep functions small and focused. A function should do one thing at one level of detail. If you need a comment to explain a block of code, that block may belong in its own function.
- Don’t repeat yourself (DRY). When the same logic appears in several places, move it into one function or class. The idea is widely attributed to The Pragmatic Programmer (1999) by Andrew Hunt and David Thomas.
- Keep it simple (KISS). Choose the simplest design that meets the current need.
- You aren’t going to need it (YAGNI). Do not build features or extra flexibility until a real requirement asks for them.
- Avoid magic numbers. Replace unexplained literal values with named constants.
- Write comments that explain why. Code shows what it does. Comments are most useful for the reason behind a decision that the code cannot show.
- Handle errors on purpose. Decide how a function reports failure, and make it clear to the caller what to do about it.
- Format code consistently. Use the same indentation, naming style and brace layout across a project, so readers can focus on the logic.
- Keep tests with the code. Tests show the expected behavior and make it safer to change the code later.
Principle 6 is easy to apply in C++. Compare a literal with a named constant:
#include <iostream>
constexpr int kMaxRetries = 3;
int main() {
for (int attempt = 1; attempt <= kMaxRetries; ++attempt) {
std::cout << "Attempt " << attempt << " of " << kMaxRetries << "\n";
}
}
The name kMaxRetries tells a reader what the 3 means, and changing the limit means editing one line.
How clean code relates to SOLID
Clean code covers many habits, from naming to formatting. SOLID is narrower. It focuses on how classes are divided and how they depend on each other. Several clean code habits, such as meaningful names and small functions, support SOLID, but they are useful on their own. For the five class-design principles and code examples, see solid principles in c.
Using a list without memorizing it
A list like this is easier to use if you work on one or two habits at a time. Pick a habit, look for it in code you are writing, and review it again later. Over time the habits tend to become a normal part of how you read and write code.