I'll Be Backend
Code smells · C#

Clean code: replace comments with code

Let the code say what it does, so no comment can drift into a lie.

16 steps5 chapters~6 min at 1.25×#comments#naming#readability#magic numbers
Language
JavaKotlinC#C++PythonRubyPHPTypeScriptJavaScriptGoRustSwift
The lesson plays right here. Pause anywhere, step back, or jump to a step below. Watch the C# video on YouTube Code on GitHub

Watch the narrated video

Every step

Problem

Steps 1–3

Refactor

Steps 4–12

Payoff

Step 13

C# bonus

Step 14

Recap

Steps 15–16

The code: before and after

Before

class CancellationPolicy
{
    public decimal Fee(Booking b, DateTime today)
    {
        // days left before check-in
        int d = (b.CheckIn - today).Days;
        // free cancellation 14 days or more before check-in
        if (d >= 14) return 0;
        // non-refundable or under 2 days out: pay in full
        if (b.Rate == 'N' || d < 2) return b.Total;
        // otherwise half the total
        decimal f = b.Total * 0.5m;
        // partner contracts require a one-night minimum
        return Math.Max(f, b.Total / b.Nights);
    }
}

After

class CancellationPolicy
{
    private const int FreeCancellationDays = 14;
    private const int LoyaltyFreeDays = 7;
    private const int LastMinuteDays = 2;
    private const char NonRefundable = 'N';

    public decimal Fee(Booking b, DateTime today)
    {
        int daysBeforeCheckIn = (b.CheckIn - today).Days;
        if (IsFreeCancellation(b, daysBeforeCheckIn)) return 0;
        if (PaysInFull(b, daysBeforeCheckIn)) return b.Total;
        decimal halfTotal = b.Total * 0.5m;
        // partner contracts require a one-night minimum
        return Math.Max(halfTotal, NightlyPrice(b));
    }

    private bool IsFreeCancellation(Booking b, int days)
        => b.Loyal ? days >= LoyaltyFreeDays
                   : days >= FreeCancellationDays;

    private bool PaysInFull(Booking b, int days)
        => b.Rate == NonRefundable || days < LastMinuteDays;

    private decimal NightlyPrice(Booking b) => b.Total / b.Nights;
}

Transcript, step by step

Problem

Step 1: A comment on every rule Before

This method works out what a hotel guest pays when they cancel a booking. Cancelling is free from fourteen days out, costs the full price on a non-refundable rate or under two days, and otherwise costs half, but never less than one night. Every rule has a comment above it, and each comment tells you what the next line does. It works, the tests pass, and it looks well documented.

Step 2: The comment still says 14 Code smell

Loyalty members now get free cancellation from seven days out. Someone adds the rule to the if and the tests pass, but the comment above it still says fourteen days or more. A comment that says what the code does is a second copy of that code, and nothing keeps the two copies in sync. This method has four of those copies, here on the day count, here on the free rule, here on full pay, and here on the half. The next developer trusts the comment, and support ends up quoting the old fourteen day rule to a loyal guest. Review missed it too, because the diff touched the code, and nobody checks the sentence sitting above it.

Step 3: Back it out, then name things Plan

Let's back that change out. We'll refactor first and turn each comment that says what into a name in the code, so there's only one copy to keep right. Each step deletes the comment its new name replaces, and then the loyalty rule goes back in.

Refactor

Step 4: Name the day count Rename Variable

The first comment was only there because the variable was called d. So we rename d to days before check in, and the comment has nothing left to say, so it goes. Every line that reads the count now says what it is.

Step 5: Name the fourteen Replace Magic Number

Fourteen was a bare number, and only the comment said it was the free cancellation window. Now it's a constant called Free Cancellation Days, and the if reads it by name. The comment stays for now, and it goes when the whole rule gets a method of its own.

Step 6: Name the two Replace Magic Number

The number two gets the same treatment, as a constant called Last Minute Days. The line got too long, so the second half of the condition moves down, and the logic stays the same.

Step 7: Name the rate code Replace Magic Number

The letter N is a code from the booking system, and you'd only know what it means from the comment. Naming it Non Refundable puts that meaning into the code itself.

Step 8: The free rule gets a name Extract Method

The free cancellation comment named a rule, so we give that rule a method with the same name. Fee now asks is free cancellation, and the comment above that line is gone, because the call says it. The method compares the day count to the constant, so the rule lives in one place under one name.

Step 9: Full pay gets a name Extract Method

The full pay rule gets the same move, into a method called pays in full. It needs the booking for the rate and the day count for the deadline, so it takes both. Back in fee, the call reads the way the comment did, so the comment goes.

Step 10: Name the half Rename Variable

The comment over f said it was half the total, so we call it half total and drop the comment. The max at the bottom now compares half total with something you still have to work out in your head.

Step 11: Name one night's price Extract Method

Total divided by nights is the price of one night, and the code can say so. We extract it into nightly price, so the last line reads half total or one night, whichever is more.

Step 12: One comment stays Keep the why

One comment is left, and this one stays. The line below already shows what happens, and the comment adds the reason, which is the contract with partner hotels. No variable or method name can carry that reason, so a comment like this earns its place. Delete the comments that say what the code does, and keep the ones that say why it has to.

Payoff

Step 13: Loyalty, in one place Payoff

Now the loyalty rule goes back in, and it has an obvious home. Is free cancellation takes the booking too, and loyal guests get the seven day window from a constant called Loyalty Free Days. The places that had comments now hold names, here the day count, here the free rule, here full pay, and here the half. There's no comment left that could still say fourteen, so this change can't leave a lie behind. Pays in full and nightly price didn't change, and fee only passes the booking along.

C# bonus

Step 14: Expression-bodied members C# bonus

Each helper we extracted is a single rule, but with C# braces on their own lines, every one of them takes four lines. An expression-bodied member drops the braces and the return, so an arrow points straight at the rule. Is free cancellation had two returns, so its if becomes one conditional expression that picks the window for loyal guests. This works while a helper is one expression, and once a rule needs several statements, the braces come back.

Recap

Step 15: Where we started, where we ended Before / after

On the left, every line came with a comment saying what it did. That made two copies of each rule, and the fourteen day one was the first to go stale. On the right, fee reads as three named calls, and the only comment left gives the contract reason. The rules live in small members and constants, so changing a rule changes its description too.

Step 16: When to reach for it Takeaways

Turn a comment into code when it tells you what the next line does. Keep it when it explains why, like a contract, a bug workaround or a law, and keep the docs on a public API. You'll spot the need in a comment over a short block, a one-letter variable, or a bare number in a condition. .NET's Time Span names its units, so Time Span from days fourteen needs no comment telling you it's two weeks.