DEV Community

Timevolt
Timevolt

Posted on

The Matrix of Comments: Writing Code That Doesn't Need Comments

The Quest Begins (The "Why")

I remember the first time I opened a legacy codebase and saw a wall of comments stacked like ancient runes. Every line had a note explaining what the next line did, why a variable existed, or what the developer had eaten for breakfast that day. I felt like I was deciphering a spell book written in a language I didn’t know. I spent hours trying to understand the flow, only to find that half the comments were outright wrong—updated code, stale notes. It was maddening!

That frustration sparked a question: What if the code could speak for itself? What if I could look at a function and instantly grasp its intent without needing a translator? That quest led me to a simple, powerful best practice that changed the way I write code forever: make the code self‑documenting through intention‑revealing names and tiny, focused functions.

The Revelation (The Insight)

The insight was deceptively simple: comments are a liability, not a safety net. They can become outdated, they add noise, and they often mask poorly named variables or tangled logic. When you rename a variable to reflect its purpose, or extract a block of logic into a function whose name tells the story, the comment becomes redundant—sometimes even harmful because it drifts away from reality.

Think of it like this: if you had to explain every step of a recipe to a friend, you’d quickly realize that naming the ingredients clearly (“two cups of flour”, “one teaspoon of salt”) does most of the work. The same holds for code. The moment I started treating names as the primary documentation, I felt a weight lift. Bugs became easier to spot because the code itself told the truth.

I was shocked at how quickly my teammates began to understand my changes without me having to write a single line of explanation. It felt like finding the One Ring—suddenly, the invisible power was right there in front of me.

Wielding the Power (Code & Examples)

Let’s look at a real‑world snippet that made me cringe before I applied this practice.

Before – The Comment‑Heavy Struggle

// Calculate the total price for a shopping cart
// Input: cartItems is an array of objects { id: [{id:number, name:string, price:number, quantity:number}, ...]
// taxRate is a decimal like 0.08 for 8%
// discountCode is a string like "SAVE10" or null
// Returns the final amount the customer should pay, rounded to 2 decimals
function calculateTotal(cartItems, taxRate, discountCode) {
  // Step 1: sum the line totals (price * quantity)
  let subtotal = 0;
  for (let i = 0; i < cartItems.length; i++) {
    // Multiply price by quantity for each item
    subtotal += cartItems[i].price * cartItems[i].quantity;
  }

  // Step 2: apply tax
  let tax = subtotal * taxRate;

  // Step 3: apply discount if a valid code is present
  let discount = 0;
  if (discountCode === "SAVE10") {
    discount = subtotal * 0.10; // 10% off
  } else if (discountCode === "SAVE20") {
    discount = subtotal * 0.20; // 20% off
  }

  // Step 4: compute total before rounding
  let total = subtotal + tax - discount;

  // Step 5: round to two decimal places (currency)
  return Math.round(total * 100) / 100;
}
Enter fullscreen mode Exit fullscreen mode

Sure, the comments explain each step, but look at the noise: variables named subtotal, tax, discount, total are okay, yet the logic is buried in a long function with inline comments that repeat what the code already says. Worse, if someone changes the tax calculation but forgets to update the comment, the comment becomes a lie.

After – Self‑Documenting Code

function calculateTotal(cartItems, taxRate, discountCode) {
  const subtotal = sumLineTotals(cartItems);
  const tax = calculateTax(subtotal, taxRate);
  const discount = applyDiscount(subtotal, discountCode);
  const rawTotal = subtotal + tax - discount;
  return roundToTwoDecimals(rawTotal);
}

// ----- tiny, intention‑revealing helpers -----
function sumLineTotals(items) {
  return items.reduce((sum, item) => sum + item.price * item.quantity, 0);
}

function calculateTax(amount, rate) {
  return amount * rate;
}

function applyDiscount(amount, code) {
  switch (code) {
    case "SAVE10": return amount * 0.10;
    case "SAVE20": return amount * 0.20;
    default: return 0;
  }
}

function roundToTwoDecimals(value) {
  return Math.round(value * 100) / 100;
}
Enter fullscreen mode Exit fullscreen mode

What changed?

  • Function names now narrate the story: sumLineTotals, calculateTax, applyDiscount, roundToTwoDecimals.
  • Variables are named for what they hold, not how they’re used (subtotal, tax, discount, rawTotal).
  • The main calculateTotal reads like a high‑level recipe: get the subtotal, add tax, subtract discount, round.
  • No comments needed—if you rename a helper, the name itself tells you what it does.

If a teammate later changes the discount logic, they only need to touch applyDiscount. The comment‑free main function stays accurate because its structure reflects the intent.

Why This Matters (and What Happens When You Get It Wrong)

When you rely on comments, you invite a class of bugs I call “comment‑drift”: the code evolves, the comment doesn’t, and future readers (or your future self) are misled. I once spent three hours chasing a bug where a comment said “apply 15% discount for loyalty members,” but the code actually gave 10% because the promo had changed. The comment was a comforting lie that sent me down the wrong rabbit hole.

By contrast, self‑documenting code makes the truth visible at a glance. Refactoring becomes safer because you can rename a function and instantly see where it’s used. Onboarding new developers is faster—they don’t need to decode a commentary track; they just read the flow.

And the best part? It feels empowering. Writing code that tells its own story is like wielding a lightsaber: you cut through complexity with precision and confidence.

Why This New Power Matters

Adopting this practice transforms how you think about every line you write. You start asking: Does this name reveal its intent? If the answer is no, you refactor. You begin to see functions as verbs and variables as nouns, crafting a readable narrative that anyone can follow.

Your codebase becomes a living document—no more outdated comments, no more “what does this do?” moments. You’ll spend less time explaining and more time building cool features.

Give it a try on your next function: rename a vague variable, extract a block into a well‑named function, then delete the comment that explained it. Notice how the intent shines through.

Challenge: Pick one piece of code you’ve written recently that leans heavily on comments. Refactor it using intention‑revealing names and tiny helpers. Share your before/after in the comments—let’s see how much clearer it gets! Happy coding!

Top comments (0)