On this page
- Clean code principles
- 1. Names that say what a thing is
- 2. Functions that do one job
- 3. Shallow nesting and early returns
- 4. One home for each piece of knowledge
- 5. Clear error handling
- 6. Comments that explain why
- 7. Consistent formatting
- 8. Tests that document behavior
- 9. Clear boundaries and dependencies
- Clear code: readability over cleverness
- What the Clean Code book gets right, and where it overreaches
- How to write clean code day to day
- How to measure clean code
- Tools that help
- FAQ
Clean code is code that another developer can read, change and trust without asking the author what it does. It has names that say what things are, functions that do one job, shallow control flow, no duplicated knowledge and tests that show how it behaves.
The phrase comes from Robert C. Martin's book of the same name, and most pages that rank for it are summaries of that book. This guide is about the practice: nine principles with before and after code, the places where the usual advice goes too far, a daily routine, and how to measure whether a codebase is getting cleaner. For the wider picture, see the code quality guide.
Clean code principles
Clean code comes down to a few habits applied every day, and none of them need a framework or a tool. The examples below are Python and TypeScript, but the habits carry to any language.
1. Names that say what a thing is
A good name lets you skip reading the body. If you have to open the function to learn what it returns, the name failed.
# before
def calc(d, r):
return d - d * r
# after
def price_after_discount(price, discount_rate):
return price - price * discount_rate
A name should be as long as its scope. i in a three-line loop is fine. A module-level constant called T is not. Name booleans as questions (is_expired, has_access) and functions as verbs. If you cannot name something without "and" or "manager" or "handler", the thing probably does too much.
2. Functions that do one job
A function should do one thing at one level of detail. The test is whether you can describe it in a sentence without "and".
# before
def process_order(order):
if not order.items:
raise ValueError("empty order")
total = sum(i.price * i.qty for i in order.items)
if order.coupon:
total -= total * order.coupon.rate
db.save(order, total)
mailer.send(order.email, f"Total: {total}")
# after
def process_order(order):
validate(order)
total = order_total(order)
db.save(order, total)
send_receipt(order, total)
The second version reads like an outline. Each helper is small enough to test alone, and you never read coupon math next to an email call.
Here is where the standard advice goes too far. Some readers take "small functions" to mean four lines each, and you end up with a chain of nine one-line helpers that you open one by one to follow a single path. That is harder to read than the forty-line function it replaced. Split when a piece has a name worth giving it and a reason to change on its own. Do not split to hit a line count.
3. Shallow nesting and early returns
Every extra level of indentation is something the reader has to hold in their head. Return early on the failure cases and keep the main path flat.
// before
function discount(user: User | null, cart: Cart): number {
if (user) {
if (user.isActive) {
if (cart.items.length > 0) {
return cart.total * user.tier.rate;
}
}
}
return 0;
}
// after
function discount(user: User | null, cart: Cart): number {
if (!user || !user.isActive) return 0;
if (cart.items.length === 0) return 0;
return cart.total * user.tier.rate;
}
Same behavior, one level instead of three, and the happy path is the last line. This one habit does more for readability than any naming rule, and the data later in this guide shows why: deep nesting travels with high complexity almost everywhere. Cognitive complexity exists to charge for exactly this.
4. One home for each piece of knowledge
Do not repeat yourself means every piece of knowledge has one place where it lives. It is about knowledge, not about lines of text that happen to look alike.
# before: the tax rule lives in three places
cart_total = subtotal * 1.0825
invoice_total = subtotal * 1.0825
email_total = subtotal * 1.0825
# after
SALES_TAX = 0.0825
def with_tax(subtotal):
return subtotal * (1 + SALES_TAX)
Now the counterpoint, because it is where teams get hurt. Two blocks that look the same today but change for different reasons are not duplication. Merge them into one function with a flag, then a second flag, then a third, and you have an abstraction that fits neither caller. Sandi Metz put it well: duplication is far cheaper than the wrong abstraction. My rule is to copy once, abstract on the third occurrence, and only when the three agree on why they change.
5. Clear error handling
Fail loudly, early and with a message that names what went wrong. Swallowed errors are the most expensive kind of unclean code, because the failure shows up three layers away from its cause.
# before
try:
config = load(path)
except Exception:
config = {}
# after
try:
config = load(path)
except FileNotFoundError:
raise ConfigError(f"config not found at {path}") from None
Catch the specific exception you can handle and let the rest propagate. Do not return None to signal failure when the caller will forget to check it. Do not log an error and also re-raise it at every layer, or one failure fills the log with the same line five times.
6. Comments that explain why
Code says what it does; a comment should say why it does it that way. A comment that restates the line is noise that goes stale.
# before
i += 1 # increment i
# after
# The vendor API is 1-indexed but our rows are 0-indexed.
page = row_index + 1
Good comments record a constraint, a bug you worked around, or a decision a reader would otherwise undo. Some Clean Code advice treats every comment as a failure to write clear code. That is too strict. If the reason lives only in your head, the next person will "simplify" it and break production. When a comment explains what, rename or extract instead.
7. Consistent formatting
Settle formatting once, with a tool. Pick a formatter, run it on save and in CI, and stop discussing it. Consistency lets a reviewer's eyes land on logic instead of whitespace.
Use the community default for the language: Ruff format or Black for Python, Prettier for JavaScript and TypeScript, gofmt for Go, rustfmt for Rust. Pair it with a linter for the issues a formatter cannot fix, such as unused variables and unreachable code. Your team's rules on naming and structure belong in coding standards, written down once.
8. Tests that document behavior
A good test is the most reliable documentation you have, because it fails when it is wrong. Name tests after the behavior, not the function.
def test_expired_coupon_is_rejected():
...
def test_empty_cart_has_no_discount():
...
Read as a list, those names tell a new developer what the code promises. They also make refactoring safe, and clean code is mostly code you can change safely. A suite that mirrors the implementation line by line does the opposite: every refactor breaks fifty tests that were never about behavior.
9. Clear boundaries and dependencies
Keep the parts that change often away from the parts that do not. Business rules should not import the web framework. A function that computes a price should not open a database connection.
// before: logic welded to I/O
async function totalFor(orderId: string) {
const rows = await db.query("select * from items where order_id = $1", [orderId]);
return rows.reduce((sum, r) => sum + r.price * r.qty, 0);
}
// after: logic takes data in and returns data out
function totalFor(items: Item[]): number {
return items.reduce((sum, i) => sum + i.price * i.qty, 0);
}
The second function needs no database in its test. Pass dependencies in, keep modules pointing one direction, and watch for coupling and cohesion problems: when a change in one file always drags three others along, a boundary is in the wrong place.
Clear code: readability over cleverness
Clear code is code whose intent is obvious on the first read. It is the working goal behind the nine habits, and it beats cleverness every time.
# clever
result = [x for x in (y for y in data if y) if x.active and not x.deleted][:10]
# clear
active = [item for item in data if item and item.active and not item.deleted]
result = active[:10]
Both do the same thing, and only one can be read at speed. Dense one-liners, nested ternaries and tricks that lean on operator precedence save you ten seconds and cost the next reader ten minutes. Code is read far more often than it is written, so the trade is bad.
A useful check: could a teammate who did not write this explain it back to you after one read? If not, it is not clear yet, whatever its metrics say.
What the Clean Code book gets right, and where it overreaches
The book is worth reading for its taste, not as a rule list. Robert C. Martin's Clean Code: A Handbook of Agile Software Craftsmanship was first published in 2008. Pearson lists a second edition from Addison-Wesley Professional in 2025, a rewrite with new material on testing, design and several languages.
What holds up: names matter, functions should be short and focused, tests are part of the design, and leaving code cleaner than you found it compounds. What gets applied badly: the push toward very small functions, the idea that comments are always a failure, and examples that suit Java more than they suit your language. Take the principles, test them against your own codebase, and drop the ones that make your code harder to follow. If a rule makes a function worse, the rule loses.
How to write clean code day to day
Clean code is a habit you keep up in small steps, not a cleanup project. Big rewrites tend to leave a second mess. This is the routine that works.
A checklist before you open a pull request:
- Can I name every function and variable in this diff without "and", "data" or "temp"?
- Does each function fit on one screen and do one job?
- Is the deepest nesting three levels or fewer?
- Did I copy a block a third time, and is it the same knowledge?
- Does every
exceptorcatchhandle something specific? - Do the comments explain why, and do the tests describe behavior?
- Did the formatter and linter pass without suppressions?
Then the habits around the checklist:
- Refactor in small steps. Rename, extract one function, run the tests, commit. A step you can finish in ten minutes is a step you will take. The refactoring guide covers the safe order.
- Clean the code you touch. If you are changing a file for a feature, leave it a bit better. Do not open a separate branch to clean files nobody is editing.
- Use review for taste. Tools catch the mechanical problems, so reviewers can spend their attention on names, boundaries and whether the code reads clearly. A pull request checklist keeps the list consistent.
- Automate what can be automated. Formatter on save, linter in CI, and a complexity limit that fails the build above a threshold you can meet today. Tighten it over time.
- Recognize the smells. Long functions, flag arguments, shotgun edits and god classes are the usual signs. The code smells guide lists them with fixes.
If the codebase is already tangled, start with the worst offenders and skip the blanket sweep. The spaghetti code guide covers how to untangle in order.
How to measure clean code
Cleanliness is partly taste, but the parts that cost you are measurable: complexity, nesting, file size and how often a file changes. We pulled per-file numbers for 200,744 production files across 160 popular public repos (1,000+ stars, measured November 2026; tests, generated and vendored code excluded). Two definitions: max_ccn is the highest cyclomatic complexity of any single function in the file, and nesting is the deepest level of nested control flow in the file.
Most code is small and flat. Half of all files have a worst function of complexity 4 or less. The median file's deepest nesting is 1, and the p90 file's is 4. In the 200,715-file size cut, half of all production files are 64 non-comment lines or fewer, and only 2.1% pass 1,000. A typical file in a healthy popular repo is short, flat and plain.
Nesting is where files turn. 77.64% of files nest at most two levels, and just 10.48% of those hold a function above McCabe's limit of 10. At three levels, 57.21% do. At four or more, 80.67% do.
| Deepest nesting in file | Share of files | Median non-comment lines | Has a function above 10 |
|---|---|---|---|
| 0 to 2 | 77.64% | 44 | 10.48% |
| 3 | 12.35% | 174 | 57.21% |
| 4 or more | 10.01% | 290 | 80.67% |
Scroll the table sideways to see every column.
This is the early-return rule in numbers. Past three levels, files are bigger and almost always carry a complicated function, so keeping nesting at three or fewer is a cheap proxy for staying under complexity limits.
Size tracks the mess. The size figures come from a slightly narrower cut of the same repos, 200,715 files (the 29 files from two repos under the 50-file minimum drop out). Files over 1,000 non-comment lines are 2.1% of it and carry a lot of the pain.
| File size (non-comment lines) | Files | Median health (0-10) | Has a function above 10 | Health below 4 |
|---|---|---|---|---|
| 1 to 200 | 160,220 | 9.85 | 13.3% | 0.54% |
| 201 to 500 | 28,528 | 7.55 | 58.4% | 9.64% |
| 501 to 1,000 | 7,834 | 5.37 | 70.0% | 34.34% |
| over 1,000 | 4,133 | 2.72 | 77.5% | 60.51% |
Scroll the table sideways to see every column.
One caution on the health column: health is repowise's 0 to 10 file score, and size and complexity are among its inputs, so it shows how the score treats big files and is not independent proof that big files have more bugs. The independent column is the raw function count: 77.5% of files over 1,000 lines hold a function above 10, against 13.3% of files of 200 lines or fewer.
A file's size and nesting are warning signs you can read before you read a line of it. Where those meet heavy git churn, you have the files that deserve your next hour. That is the idea behind code churn and hotspot analysis, and it is how repowise ranks files: a code health score per file plus the history of how often each one changes, so the fix-first list is the mess that costs you.
Tools that help
Tools enforce the mechanical half of clean code so reviews can focus on the rest.
| Job | Python | JavaScript and TypeScript | Go |
|---|---|---|---|
| Formatter | Ruff format, Black | Prettier | gofmt |
| Linter | Ruff, pylint | ESLint | golangci-lint |
| Complexity | radon, Ruff C901 | ESLint complexity | gocyclo |
Scroll the table sideways to see every column.
A linter catches unused code and risky patterns, a formatter ends whitespace arguments, and a complexity rule keeps functions from growing. None of them judge names or boundaries, which is why review still matters.
FAQ
- What is clean code?
- Clean code is code that another developer can read, change and trust without asking its author what it does. It uses descriptive names, small focused functions, shallow control flow, one source for each piece of knowledge and tests that describe its behavior. The term was popularized by Robert C. Martin's 2008 book Clean Code.
- What are clean code principles?
- The core principles are meaningful names, functions that do one thing, shallow nesting with early returns, no duplicated knowledge, explicit error handling, comments that explain why, consistent formatting, tests as documentation and clear boundaries between modules. Use them as habits, and drop any that make your own code harder to read.
- How do you write clean code?
- Name things for what they are, keep each function to one job, return early to keep nesting at three levels or fewer, and handle errors specifically. Run a formatter and linter in CI, write tests named after behavior, and refactor in small steps whenever you touch a file.
- Is Clean Code (the book) still worth reading?
- Yes, for its taste: names, short focused functions and tests matter in any language. Read it critically, because some advice, like very tiny functions and treating comments as failure, goes too far, and many examples are Java. A second edition from Addison-Wesley Professional was published in 2025.
- What does it mean to clean up code?
- Start with the files that change most and hurt most, not the whole codebase. Add tests around the behavior, then make small steps: rename, extract, flatten nesting, delete dead code, and run the tests after each. Commit each step separately so you can undo one cleanly.
- What are the five principles of clean code?
- There is no official list of five. The usual five are SOLID: single responsibility, open/closed, Liskov substitution, interface segregation and dependency inversion. Those are object-oriented design principles that support clean code. The everyday habits are the nine above, and the first four (names, one job per function, shallow nesting, one home for each piece of knowledge) do most of the work.
- What is the 80/20 rule in coding?
- It is the Pareto principle applied to software: roughly 80% of the problems come from 20% of the code. In practice a small set of files holds most of the complexity and most of the changes. In the median repo we measured, the top 10% of files hold 87% of the complexity above McCabe's limit, so cleaning that short list pays most.
- What is code refactoring?
- Code refactoring is changing the structure of code without changing what it does, so it is easier to read and change. Renaming, extracting a function and flattening nesting are all refactorings. Tests protect behavior while you do it. See the refactoring guide.
- What is the difference between clean code and clear code?
- Clear code is the goal and clean code is the practice. Clear code is obvious on a first read. Clean code is the set of habits, such as good names, small functions and shallow nesting, that produce it. Cleverness that saves lines but costs reading time is neither.



