Skip to main content
CodingMarble

Programming fundamentals

Clean Code Principles: A Practical Guide With Examples

Clean code is code that the next person, often you in six months, can read, change and trust without first decoding it. The habits that matter most are honest names, small focused functions, comments that explain why, deliberate error handling and tests that let you refactor without fear.

By CodingMarble · Published · 5 min read

A laptop turned on showing code
Photo: Andras Vas on Unsplash

What clean code is for

Code is read far more often than it is written. Every change begins with someone reading what is already there and trying to work out what it does and what would break. Clean code reduces the cost of that reading. It is not about elegance or cleverness, and it is not a checklist you can pass or fail. It is a set of habits that make intent visible.

A useful test is to hand a function to a colleague who has not seen it and ask them to explain it back. If they get it right in a minute, the code is communicating. If they need to run it in a debugger to be sure, something is hiding. The sections below are the habits that move code from the second situation to the first.

Names carry most of the meaning

A name should say what a thing is or does in the language of the problem. A variable called d tells the reader nothing, while daysUntilExpiry tells them the unit and the meaning. Functions are actions, so name them with verbs: calculateTotal, sendReceipt. Booleans read best as questions: isPaid, hasAccess. Avoid names that differ only in a vague suffix, such as data, data2 and dataNew, because a reader cannot tell which to trust.

Keep one word per concept across the codebase. If one file says fetchUser, another getUser and a third loadUser for the same idea, readers wonder whether they differ. When a name needs a long comment to explain it, rename the thing instead. Renaming is the cheapest refactor available, and modern editors do it safely across files.

Small functions and one level of abstraction

A function should do one thing and stay at one level of abstraction. The trouble is not length alone. A twenty-line function that mixes validation, arithmetic, formatting and a database call forces the reader to hold four ideas at once. Splitting it so that each piece has a name lets the top-level function read like an outline of the steps, while the details live one level down. Do not split mechanically to hit a line count, though. A function that is fifteen lines of one clear idea is better than five three-line fragments that you must jump between to follow.

Here is a realistic before and after. The first version works, but the reader must parse discount rules, tax and formatting in one pass.

JavaScript· Before: one function mixing rules, arithmetic and output
function f(o) {
  let t = 0;
  for (let i = 0; i < o.items.length; i++) {
    t = t + o.items[i].p * o.items[i].q;
  }
  if (o.c === "GOLD") { t = t - t * 0.1; }
  else if (o.c === "SILVER") { t = t - t * 0.05; }
  t = t + t * 0.18;
  return "Total: " + t.toFixed(2);
}
JavaScript· After: named constants, named steps, same behaviour
const DISCOUNT_BY_TIER = { GOLD: 0.1, SILVER: 0.05 };
const TAX_RATE = 0.18;

const subtotal = (items) =>
  items.reduce((sum, { price, quantity }) => sum + price * quantity, 0);

const applyDiscount = (amount, tier) =>
  amount * (1 - (DISCOUNT_BY_TIER[tier] ?? 0));

const addTax = (amount) => amount * (1 + TAX_RATE);

function formatOrderTotal(order) {
  const discounted = applyDiscount(subtotal(order.items), order.tier);
  return "Total: " + addTax(discounted).toFixed(2);
}

console.log(formatOrderTotal({ tier: "GOLD", items: [{ price: 100, quantity: 2 }] }));
// "Total: 212.40"

The behaviour is the same, but the rules now have names and a single home. Adding a new tier means editing one object, not hunting through an if chain. The top function reads as three steps. Notice also that the magic numbers 0.1 and 0.18 became constants whose names say what they mean.

Duplication versus the wrong abstraction

Repeating the same business rule in five places is a real hazard: someone will fix four of them. But merging code too early is the opposite mistake. Two blocks that look alike today may be similar only by coincidence, and once you fuse them into one function with flags and options to cover both cases, the shared function becomes harder to read than the duplication was. A practical rule is to tolerate similar code the first and second time, and extract when a third use shows what is genuinely common. Duplicate knowledge is the thing to remove, not duplicate text.

Practical tip: if a helper function grows a boolean parameter that switches its behaviour, or the list of options keeps lengthening, that is often a sign that two different things were merged. Splitting them back into two clear functions is usually cleaner than adding another flag.

Comments that explain why, and errors that speak up

A comment that restates the code, such as add one to i, adds noise and goes stale. A useful comment records what the code cannot say: why this approach, which bug it avoids, which external system forces this odd format, or a link to the relevant specification. If you feel the urge to explain what a block does, try extracting it into a well-named function first, and keep the comment for the reasoning.

Error handling is part of readability. Do not swallow errors with an empty catch block, because the failure will appear later, far from its cause. Fail early with a clear message that names the bad value, validate inputs at the boundary where data enters your system, and throw or return errors in one consistent style across a module. Return null or false for one kind of failure and throw for another, and every caller must remember which. Messages should help the person reading the log: include what was expected and what was received.

Formatting and refactoring with a safety net

Consistent formatting is best handled by a tool, not by review comments. Use an automatic formatter and a linter, agree on the configuration once, and let the machine end style arguments. Then human review time goes to naming and design.

Refactoring means changing structure without changing behaviour, and the only way to know behaviour held is a test. The safe sequence is to write or confirm tests that pin down the current behaviour, make one small structural change, run the tests, and repeat. Commit after each green step so that a bad step is easy to undo. Mixing a refactor with a feature or a bug fix in one change makes review hard and bugs hard to locate, so keep them separate commits at least. If the code has no tests and you must change it, write a few characterisation tests that record what it currently returns, even if the behaviour is odd, before touching anything.

Where clean code dogma goes wrong

Rules of thumb become harmful when they are treated as laws. Extracting every three lines into its own function can scatter a single idea across ten files. Forcing every class to implement an interface, even when there is only one implementation and no plan for another, adds indirection that readers must trace. A rule like functions must be under ten lines ignores that some algorithms are clearest as one continuous block. Performance-critical code sometimes needs a less tidy shape, and when it does, a comment explaining why and a benchmark showing the gain keep it honest.

The purpose is communication. When a rule helps a real reader understand the code, follow it. When following it makes the code harder to follow, the rule is the problem. Judge each change by one question: would the next developer find this easier to understand than before?

Need this built properly for your business?

CodingMarble is a remote studio in India that builds websites, apps and games on fixed packages with the scope written down before payment. Try the free tools we run, or start a project when you are ready.