Clean Code Principles: Naming, Functions, Classes
A practical guide to clean code principles: meaningful names, small functions, single responsibility, useful comments, error handling, DRY, and formatting.
Introduction
Most code is read far more often than it’s written — a function you write once will be read by teammates, reviewers, and your future self dozens of times. Every minute a reader spends deciphering a name or tracing a side effect is a minute of maintenance cost you just added to the project. Clean code is the discipline of reducing that cost: code that states what it does, does only what it says, and stays easy to change.
The term was popularized by Robert C. Martin’s Clean Code (2008), but the underlying principles — small functions, intention-revealing names, single responsibility — come from decades of practice and show up in every serious codebase, regardless of language or framework. They’re also the same smells that linters, code review checklists, and refactoring guides keep pointing at.
This guide walks through the principles that pay for themselves fastest: naming, functions, classes, comments, error handling, DRY, and formatting. For each one you will see the rule, why it exists, a before/after example, and — just as important — when the rule can be bent. Principles are tools, not commandments, and the last section covers where teams routinely take them too far.
Each layer depends on the one below — a class full of well-named methods is still a mess if the methods each do five things, and SOLID advice is wasted on code where data and helper are doing the naming.
Meaningful Names
Names are the cheapest documentation you’ve got. A good name answers three questions at once: what the thing holds, what it’s for, and why it exists — so the reader never has to scroll back to the declaration to find out.
Use intention-revealing names
A name should tell you what it means without a comment propping it up.
// BAD: the comment carries the meaning the name should carry
const d = 5; // elapsed time in days
const total = d * 24 * 60 * 60;
// GOOD: the name carries it
const elapsedTimeInDays = 5;
const totalSeconds = elapsedTimeInDays * 24 * 60 * 60;
The same applies to functions. calc(a, b) forces every call site to explain itself; calculateTotalPrice(quantity, unitPrice) explains itself.
Avoid disinformation
A name that lies is worse than no name at all. accountList that’s actually a Set will make someone write accountList[0] six months from now.
// BAD: not a List
const accountList = new Set<Account>();
// GOOD: name matches the structure, or stays neutral
const accountSet = new Set<Account>();
const accounts = new Set<Account>();
Use pronounceable and searchable names
If you can’t say genYmdhms out loud in a code review, rename it. And if the literal 5 means “senior engineer”, burying it in a comparison makes it impossible to find later — you can’t grep for a number’s meaning.
// BAD: unpronounceable timestamp + magic number
const genYmdhms = new Date();
if (employee.type === 5) {
giveBonus(employee);
}
// GOOD: sayable name + named constant you can grep for
const generationTimestamp = new Date();
const SENIOR_ENGINEER = 5;
if (employee.type === SENIOR_ENGINEER) {
giveBonus(employee);
}
Pick one word per concept
Consistency matters more than the exact word. If you call it fetch in one module, get in another, and retrieve in a third, readers will assume the three mean different things — because that’s what inconsistent vocabulary usually signals.
| Concept | Pick one | Avoid mixing |
|---|---|---|
| Fetch data | get or fetch | get + fetch + retrieve |
| Create an object | create or make | create + build + newX |
| Insert data | insert or add | insert + add + append |
| Remove data | remove or delete | remove + delete + destroy |
Classes are nouns, methods are verbs
A class names a thing or a role (OrderProcessor, PaymentValidator). A method names an action (processOrder, validatePayment). When you see class ProcessOrder, that’s a function wearing a class costume — it will grow static fields and hidden state until someone splits it.
// GOOD
class OrderProcessor {
processOrder(order: Order): void { /* ... */ }
}
// BAD: verb as a class name — the "class" is really a function
class ProcessOrder { }
Functions
If there’s one principle that dominates all the others, it’s this: functions should be small, do one thing, and do it at one level of abstraction. Almost every other clean-code rule is a consequence of those three.
Small and focused
A function that validates, calculates, persists, and emails is four functions pretending to be one. Each responsibility is a separate reason to change, a separate place for a bug, and a separate thing a test must cover.
// BAD: validation + tax + discount + persistence + email in one function
function processOrder(order: Order): void {
if (!order.items || order.items.length === 0) {
throw new Error('Order has no items');
}
let tax = 0;
for (const item of order.items) {
if (item.category === 'food') tax += item.price * 0.05;
else if (item.category === 'electronics') tax += item.price * 0.18;
else tax += item.price * 0.10;
}
if (order.customer.isVip) order.total *= 0.90;
db.query('INSERT INTO orders ...', order);
emailService.send(order.customer.email, 'Order confirmed', order);
}
// GOOD: the orchestrator reads like a table of contents
function processOrder(order: Order): void {
validateOrder(order);
const tax = calculateTax(order.items);
applyDiscount(order);
saveOrder(order);
sendConfirmationEmail(order);
}
function calculateTax(items: Item[]): number {
const taxRates: Record<string, number> = {
food: 0.05,
electronics: 0.18,
default: 0.10,
};
return items.reduce(
(sum, item) => sum + item.price * (taxRates[item.category] ?? taxRates.default),
0,
);
}
Notice what the refactor bought you: the tax table is now testable in isolation, the orchestrator reads top-to-bottom at one level of abstraction, and adding a gift wrap step no longer means editing three code paths at once.
Few parameters
Three parameters is a sensible ceiling. Past that, a parameter object turns a positional argument list into self-describing data — and makes adding a seventh field a one-line change instead of a signature change in every caller.
// BAD: six positional parameters, caller has to remember the order
function createOrder(
customerId: string, items: Item[], shipping: Address,
billing: Address, method: string, coupon: string | null,
): Order { /* ... */ }
// GOOD: a parameter object
interface CreateOrderRequest {
customerId: string;
items: Item[];
shippingAddress: Address;
billingAddress: Address;
paymentMethod: string;
couponCode?: string;
}
function createOrder(request: CreateOrderRequest): Order { /* ... */ }
No hidden side effects
A function named checkPassword shouldn’t also start a session. The reader trusts the name; the moment a “check” mutates state, every caller becomes a potential bug report.
// BAD: validation that secretly initializes a session
function checkPassword(user: User, password: string): boolean {
if (user.password === hash(password)) {
session.initialize(user); // side effect!
return true;
}
return false;
}
// GOOD: query and command separated
function validatePassword(user: User, password: string): boolean {
return user.password === hash(password);
}
function login(user: User, password: string): Session {
if (!validatePassword(user, password)) {
throw new Error('Invalid credentials');
}
return session.initialize(user);
}
That’s command-query separation in practice: a function either does something or answers something, not both. The same rule explains why setAttribute returning boolean is a smell — callers can’t tell if the true means “it worked” or “it was already set”.
Classes
Classes fail in the same way functions do, just slower: they accumulate responsibilities until nobody knows what the class is for anymore.
Single Responsibility Principle
A class should have one reason to change. If OrderManager handles processing, tax, invoicing, persistence, and email, then a tax-law change, an SMTP migration, and a schema update all touch the same file — and every touch risks the others.
// GOOD: the orchestrator delegates, each collaborator owns one concern
class OrderProcessor {
constructor(
private readonly taxCalculator: TaxCalculator,
private readonly orderRepository: OrderRepository,
private readonly emailService: EmailService,
private readonly invoiceGenerator: InvoiceGenerator,
) {}
process(order: Order): void {
order.tax = this.taxCalculator.calculate(order);
this.orderRepository.save(order);
this.emailService.sendConfirmation(order);
this.invoiceGenerator.generate(order);
}
}
SRP is also the entry point to the wider SOLID set — see the SOLID principles guide once this guide sinks in.
Encapsulation
Public fields are a promise you can’t keep. Once account.balance is writable, every invariant the class was supposed to enforce (“deposits are positive”, “you can’t withdraw more than you’ve got”) lives in the discipline of every caller — which is to say, nowhere.
// GOOD: private state, controlled mutations
class BankAccount {
private _balance = 0;
get balance(): number {
return this._balance;
}
deposit(amount: number): void {
if (amount <= 0) throw new Error('Deposit must be positive');
this._balance += amount;
}
withdraw(amount: number): void {
if (amount > this._balance) throw new Error('Insufficient funds');
this._balance -= amount;
}
}
Two related habits fall out of this. Tell, don’t ask: instead of if (account.status === 'overdrawn') account.lock(), give the object account.lockIfOverdrawn() — the decision lives next to the state it depends on. And the Law of Demeter: customer.orders[-1].items[0].price chains through three internals that can all change under you; a customer.priceOfLastOrderedItem() method localizes that navigation to one place.
Comments
The best comment is the one you didn’t need to write. Comments rot — code changes, comments don’t get refactored — so every comment you write is a small debt against future drift. That doesn’t mean “no comments”; it means spending them where they pay.
Comments don’t fix bad code
If you need a paragraph to explain a condition, the condition is the problem.
// BAD: comment compensates for unreadable code
// Check if employee is eligible for bonus
if (employee.flags & 0x80 && employee.yearsOfService > 5) {
giveBonus(employee);
}
// GOOD: the code says what the comment was trying to
if (employee.isEligibleForBonus()) {
giveBonus(employee);
}
Write comments that explain why
The valuable comments are the ones the code can’t say: why this approach was chosen, what a non-obvious constraint is, what will break if you change it.
// GOOD: explains the why — benchmarks, constraints, warnings
// Binary search because the list is sorted and large (>10k items);
// linear scan measured 50ms slower on production-size inputs.
function findItem(sortedItems: Item[], target: string): Item | null {
// ...
}
On the flip side, i++ // increment i, commented-out code (“we might need it later” — git remembers), and Javadoc that restates the signature are all noise that readers learn to skip — which teaches them to skip the comments that matter too.
Error Handling
Error paths are code too, and they get read under worse conditions than the happy path — during an incident, at 2 a.m., by someone who didn’t write them.
Use exceptions, not error codes
Return codes force every caller to check, and callers forget. An unchecked E_LOCKED silently converts “operation failed” into “operation succeeded with a weird result”.
// GOOD: the happy path stays linear, errors have one home
function deletePage(page: Page): void {
if (page.isLocked) throw new PageLockedException(page.id);
if (!page.exists) throw new PageNotFoundException(page.id);
page.delete();
}
try {
deletePage(page);
} catch (error) {
if (error instanceof PageLockedException) handleLockedPage(error);
else if (error instanceof PageNotFoundException) handleMissingPage(error);
else throw error;
}
Notice the else throw error — the flip side of using exceptions is not swallowing them. An empty catch {} or a catch (e) {} that logs nothing converts a real failure into silent data corruption. Catch the errors you can handle meaningfully; let everything else fail loudly.
Don’t return null
Every null return is a NullPointerException waiting for a caller who forgot to check. Prefer throwing for genuinely exceptional cases, or an Option/Result type when “not found” is a normal outcome.
// GOOD: missing is an exception or an explicit Option — never an ambiguity
function getCustomer(id: string): Customer {
const customer = db.query('SELECT * FROM customers WHERE id = ?', id);
if (!customer) throw new CustomerNotFoundException(id);
return customer;
}
function findCustomer(id: string): Option<Customer> {
const customer = db.query('SELECT * FROM customers WHERE id = ?', id);
return customer ? Option.some(customer) : Option.none();
}
The companion rule is don’t pass null either — calculateDiscount(null) returning 0 teaches callers that null is a valid input, and soon half your API has defensive null checks. If “no customer” is a real state, give it a name: a GuestCustomer null-object that behaves like a customer with no discount.
DRY — Don’t Repeat Yourself
Duplication is the most expensive smell in a codebase, because a bug fixed in one copy survives in all the others. When the same validation, calculation, or SQL fragment appears twice, extract it once.
// BAD: the email check exists in two places — fix one, the other stays broken
function createUser(email: string, password: string): void {
if (!email.includes('@')) throw new Error('Invalid email');
// ...
}
function updateUserEmail(userId: string, email: string): void {
if (!email.includes('@')) throw new Error('Invalid email');
// ...
}
// GOOD: one source of truth
function validateEmail(email: string): void {
if (!email.includes('@')) throw new Error('Invalid email');
}
The honest caveat: DRY is about knowledge, not lines. Two pieces of code that look identical today but change for different reasons (a signup-email rule vs. an admin-override rule) aren’t duplication — they’re coincidence, and merging them creates the wrong abstraction. The rule of thumb many teams use: extract on the third occurrence, not the second. A little duplication is cheaper than a wrong abstraction.
Formatting
Formatting is the one area where consistency beats correctness — nobody’s career was saved by tabs-over-spaces, but a file that mixes styles forces every reader to context-switch.
- Pick a formatter and stop debating. Prettier, Black, gofmt, rustfmt — run it in CI, end of discussion.
- Read top to bottom. Public interface first, private helpers below, so a file reads like a newspaper: headline, then details.
- Keep related things close. Declare variables where they’re used; a constant defined 400 lines above its only usage is a scavenger hunt.
- Limit line length. ~100 characters keeps code reviewable side-by-side and printable.
When the Principles Go Too Far
Every rule above has a failure mode, and pretending otherwise is how teams end up with AbstractSingletonProxyFactoryBean as their idea of clean code.
- Over-fragmentation: forty two-line functions that only ever call each other in sequence aren’t clean — you’ve scattered one readable algorithm across forty jumps. If splitting a function means inventing names like
doStep3a, the function was fine. - Dogmatic DRY: as covered above, merging coincidental duplication couples two things that should evolve separately.
- Longer names aren’t always better: inside a three-line block,
iis clearer thanloopIndex. Name length should scale with scope size — the farther a name travels, the more it must carry. - Comments that restate refactored code: after you fix the code, delete the comment that was compensating for it.
- Clean code isn’t a rewrite license: the Boy Scout Rule — leave the code cleaner than you found it — applies to the code you touch. Rewriting a working module because it offends your aesthetics is a risk, not a virtue, and it needs test coverage and a business reason before it needs your taste.
What Works
- Leave the code cleaner than you found it. Refactor in the same commit as the feature, not in a separate “cleanup” PR nobody will read.
- Delete dead code. Commented-out blocks, unused exports, unreachable branches — version control is the archive, not the source file.
- Write tests first. Test-driven development forces small, single-purpose functions because untestable code is almost always unclear code.
- Make reviews about readability. A code review checklist that includes “could a new hire understand this function?” catches more than any linter.
- Refactor deliberately. When you do need structural change, use proven moves — the refactoring guide catalogs the safe ones.
Common Mistakes
- Naming for the writer, not the reader:
data,info,temp,manager,helpermean nothing to anyone but the person who typed them. - Functions that grow by accretion: the function was fine at 15 lines; it’s the fifth feature added “just here” that broke it.
- Commented-out code kept “just in case”: if it’s not in git history, it’s not important enough to keep.
- Returning null as a lazy default: it exports the ambiguity to every caller.
- Deep nesting: more than three levels of indentation means the guard clauses are missing — invert the conditions and return early.
- Clean-code theater: renaming things and extracting functions without asking whether a reader is actually better off.
See Also
- Companion exercise on GitHub: a messy
OrderManagerto refactor yourself, a cleanOrderProcessorto compare against, and an ESLint config that enforces the rules mechanically. - Clean Code: A Handbook of Agile Software Craftsmanship — Robert C. Martin’s book, the source of most principles in this guide.
- Refactoring.Guru — Refactoring — catalog of smells and the refactorings that fix them.
- Martin Fowler — Refactoring — the canonical refactoring reference and its online catalog.
- SOLID principles guide — the class-design layer on top of these principles.
Frequently Asked Questions
What is clean code?
Code that a reader can understand without the author in the room: intention-revealing names, small single-purpose functions, classes with one reason to change, honest error handling, and comments that explain why, not what.
How small should a function be?
Small enough to do one thing — typically 5–20 lines. The real test: can you describe what it does in one sentence without using "and"? If not, it's got at least two jobs.
Should I write comments?
Yes, but spend them where code can't speak: why a decision was made, what constraint matters, what breaks if you touch it. Comments that restate the code are noise that trains readers to ignore the valuable ones.
What is the Single Responsibility Principle?
A class or function should have one reason to change. If OrderManager changes when tax law changes and when the SMTP provider changes and when the schema changes, it's got three responsibilities wearing one name.
Is clean code slower to write?
A little slower to write, dramatically faster to read, debug, and modify — and since code is read far more than it's written, the trade pays off by the first change request.
How do I introduce this to a team that doesn't care?
Start with the zero-debate wins: an auto-formatter in CI and a couple of naming conventions in the review checklist. Concrete diffs convince better than principles — refactor one ugly function in a PR and let the readability sell itself.
Should I refactor legacy code that isn't broken?
Touch it only where you're already changing it, per the Boy Scout Rule. Standalone rewrites need test coverage and a business justification; "it's ugly" is neither.
Does DRY mean never repeat code?
No — it means never repeat knowledge. Two similar-looking blocks that change for different reasons are coincidence, not duplication, and merging them builds the wrong abstraction. Extract on the third occurrence, not the second.
Related Resources
Refactoring Techniques: A Complete Guide
Master the essential refactoring techniques, from extract method and move function to guard clauses and polymorphism, plus a safe workflow and when not to refactor.
GuideTechnical Debt: Track, Prioritize, Pay Down
A working system for technical debt: debt register, impact-vs-effort prioritization, paydown strategies, metrics, and stakeholder reporting.
GuideCode Review Best Practices: Risk-Based Review System
A team operating guide for code review: match scrutiny to blast radius, learn from real public PR threads, handle hard conversations, and measure whether the process works.
GuideSOLID Principles Explained with Examples
Learn the five SOLID principles with bad-vs-good code examples and a full before/after refactor of a TypeScript payment service.
GuideTest-Driven Development (TDD) — A Practical Workflow
Learn TDD step by step: write a failing test, make it pass, refactor. Red-Green-Refactor with real examples in Python, JavaScript, and Java.