DEV Community

Timevolt
Timevolt

Posted on

Code Review Like a Jedi: How One Tiny Habit Changed My Code

The Quest Begins (The "Why")

Honestly, I used to dread code reviews. I’d push a branch, slap on a “looks good to me” comment, and move on, hoping nobody would notice the subtle bug lurking in a corner. Then one rainy Tuesday, a teammate pointed out a null‑reference that crashed our production service for twenty minutes. The outage cost us money, trust, and a few sleepless nights. I felt like I’d just walked into a boss fight without any gear—frustrating, embarrassing, and totally avoidable.

That moment sparked a question: What if I could change the way I write code so that reviews became a safety net instead of a scary exam? I started looking for a single habit that would ripple through everything I did—naming, structure, even how I thought about edge cases.

The Revelation (The Insight)

The game‑changer? Always write the test first—or at least sketch the assertion—before you write the implementation. Sounds simple, right? But treating the test as a living spec forces you to clarify the contract before you get lost in implementation details. It’s like drawing a map before you trek into a dungeon: you know where the traps are, you know what treasure you’re after, and you can spot when you’ve taken a wrong turn.

When I started doing this, my code reviews shifted from “did you follow the style guide?” to “does the code actually satisfy the intention we wrote down?” Suddenly, reviewers could focus on logic gaps instead of arguing over semicolons. And I, as the author, caught my own misunderstandings early—often before I even typed a single line of the real function.

Wielding the Power (Code & Examples)

Let’s look at a real‑world example: a utility that calculates the total price of a shopping cart, applying a discount if the cart contains more than five items.

The Struggle (Before)

// cartUtils.js – first draft, no test in sight
function calculateTotal(cart) {
  let subtotal = 0;
  for (const item of cart.items) {
    subtotal += item.price * item.quantity;
  }

  // Apply 10% discount if more than 5 items
  if (cart.items.length > 5) {
    subtotal *= 0.9;
  }
  return subtotal;
}
Enter fullscreen mode Exit fullscreen mode

At first glance it looks fine. But what happens when cart is null? Or when cart.items is undefined? The function will throw, and the error won’t surface until someone tries to use it in a checkout flow—potentially during a peak sale. In a review, teammates might nitpick about the variable name subtotal or ask why we didn’t use reduce, but the real safety issue stays hidden.

The Victory (After)

I started by writing a failing test that captured the intention and the edge cases I cared about:

// cartUtils.test.js – test first
describe('calculateTotal', () => {
  it('returns zero for an empty cart', () => {
    expect(calculateTotal({ items: [] })).toBe(0);
  });

  it('applies a 10% discount when more than 5 items', () => {
    const cart = {
      items: [
        { price: 10, quantity: 1 },
        { price: 20, quantity: 1 },
        { price: 30, quantity: 1 },
        { price: 40, quantity: 1 },
        { price: 50, quantity: 1 },
        { price: 60, quantity: 1 },
      ],
    };
    // Subtotal = 210, discount => 189
    expect(calculateTotal(cart)).toBeCloseTo(189);
  });

  it('throws a clear error if cart is malformed', () => {
    expect(() => calculateTotal(null)).toThrow('Invalid cart');
    expect(() => calculateTotal({})).toThrow('Invalid cart');
  });
});
Enter fullscreen mode Exit fullscreen mode

Seeing those tests fail gave me an instant checklist: handle null/undefined, guard against missing items, and make sure the discount logic is correct. Then I wrote the implementation to make them pass:

// cartUtils.js – after test‑first
function calculateTotal(cart) {
  if (!cart || !Array.isArray(cart.items)) {
    throw new Error('Invalid cart');
  }

  let subtotal = 0;
  for (const item of cart.items) {
    // Defensive: skip malformed line items
    if (item && typeof item.price === 'number' && typeof item.quantity === 'number') {
      subtotal += item.price * item.quantity;
    }
  }

  if (cart.items.length > 5) {
    subtotal *= 0.9;
  }
  return subtotal;
}
Enter fullscreen mode Exit fullscreen mode

Now the review conversation shifted dramatically:

  • Reviewer: “Nice, the guard clause makes the function fail fast with a helpful message.”
  • Me: “Yeah, I wrote the test for that case first—saved me from guessing later.”
  • Both: “Looks solid, let’s merge.”

The before/after diff isn’t just about extra lines; it’s about confidence. The test suite now serves as executable documentation, and any future change that breaks the contract will be caught instantly by the CI pipeline.

Why This New Power Matters

Adopting “test first” (or at least “assertion first”) turned my code reviews from a blame‑hunting exercise into a collaborative design session. I spend less time defending my code and more time discussing what the code should do. The side effects are glorious:

  • Fewer production bugs – edge cases are thought of upfront.
  • Faster onboarding – new teammates read the tests to understand intent.
  • Better readability – the implementation is driven by a clear spec, not by vague guesses.
  • More enjoyable reviews – we celebrate when the tests pass, not when we catch a missing semicolon.

It’s like finally getting the lightsaber training you needed before facing the Dark Side—suddenly you feel prepared, and the opponent (bugs) seems far less intimidating.

Your Turn

Give it a shot on your next small feature. Write a failing test that captures the exact behavior you want, watch it fail, then make it pass. Notice how the review conversation changes, how your own thinking sharpens, and how that little habit starts to cascade into cleaner, safer code across the board.

Challenge: Pick a function you’ve written recently that didn’t have a test. Write one test for it today—just one—and see what you discover about your own assumptions. Drop a comment below with what you learned; I’d love to hear your story!

Top comments (0)