Clean Code: Why You Should Write One (with Java Examples)

adminUpdated 5 min read
In this tutorial
  1. Uncle Bob
  2. Guidelines
  3. So what is clean code?
  4. Six clean code habits, with Java examples
  5. Tools that help
  6. The Boy Scout rule

Recently we received a call from one of our students with great feedback: a senior developer reviewing his code could not help but commend him on how clean it was.

I was also in an online town hall where a group of developers were having a meeting, and one developer was expressing his displeasure to another about some code he had written that was quite messy.

To be a well-respected developer, you need to write clean code.

Uncle Bob

Have you heard of Uncle Bob? If not, Uncle Bob (Robert C. Martin) is a well-known programmer with over 40 years of experience. He is the author of the book Clean Code and an advocate of writing software with care.

I spent an hour listening to Uncle Bob explain what clean code is, the dangers of not writing it and what it should look like. I share some of his points below.

Who remembers the Volkswagen case? If you don’t, you can read about it here. Everything we use is programmed by software, from our phones to our cards to the lift, which is why rushing is not allowed. No one should rush you, and you should not rush.

You don’t want to end up in front of a panel because you were in a hurry to push out some code. This brings me to Uncle Bob’s first point.

Guidelines

Uncle Bob says, “In a bid to go fast, we make a mess that eventually makes us go slow.” So what is the point of rushing if you will still have to come back and crack your head over the code you wrote? Slow and steady wins the race.

You should have a work ethic that lets you tell people that well-organised code takes time. Cleaning code can take as long as writing it.

“You are not done when it works, you are done when it is right.”

You just finished writing some code. Well done! But is it right? Will it be readable when the next developer picks it up? Will they feel fear or excitement when they open your code?

Getting code to work takes a lot of time, but when the code starts working you have only done half the job. You still have to go back and clean up the mess. I am pretty sure a lot of us are guilty of this. Lol.

So what is clean code?

Clean code is code that can be refactored and is easy to read. It is important that not only the computer understands what you have written, but your colleagues understand it as well.

“Clean code is simple and direct. Clean code reads like well-written prose.”

Grady Booch

“Clean code always looks like it was written by someone who cares.”

Michael Feathers

Six clean code habits, with Java examples

Ideas are easier to apply with examples, so here are six habits you can start using today.

1. Use names that reveal intent

A name should tell you why something exists and how it is used, without needing a comment.

// Before
int d; // elapsed time in days
List<int[]> list1 = getThem();

// After
int daysSinceLastLogin;
List<Cell> flaggedCells = getFlaggedCells();

If you need a comment to explain a variable, rename the variable instead.

2. Keep methods small and focused

Each method should do one thing. If you describe a method with “and” (“it validates the order and calculates tax and sends an email”), split it.

// Before: one long method doing everything
public void checkout(Order order) { /* 80 lines */ }

// After: the top-level method reads like a summary
public void checkout(Order order) {
    validate(order);
    double total = calculateTotal(order);
    paymentGateway.charge(order.customer(), total);
    notifier.sendReceipt(order.customer(), total);
}

The second version tells the story at a glance; the details live in well-named helper methods.

3. Replace magic numbers with named constants

// Before
if (age >= 18 && amount <= 500000) { ... }
double vat = price * 0.075;

// After
private static final int MINIMUM_AGE = 18;
private static final double DAILY_TRANSFER_LIMIT = 500_000;
private static final double VAT_RATE = 0.075;

if (age >= MINIMUM_AGE && amount <= DAILY_TRANSFER_LIMIT) { ... }
double vat = price * VAT_RATE;

When the VAT rate changes, you change it in one place, and the reader always knows what 0.075 means.

4. Avoid deep nesting with guard clauses

// Before
public void approve(Loan loan) {
    if (loan != null) {
        if (loan.isComplete()) {
            if (loan.score() >= 650) {
                loan.approve();
            }
        }
    }
}

// After
public void approve(Loan loan) {
    if (loan == null || !loan.isComplete()) return;
    if (loan.score() < MINIMUM_CREDIT_SCORE) return;
    loan.approve();
}

More on this in our tutorial on if, else and switch.

5. Don’t swallow exceptions

// Before: the error disappears silently
try {
    importFile(path);
} catch (Exception e) { }

// After: handle it or let it propagate with context
try {
    importFile(path);
} catch (IOException e) {
    throw new ImportFailedException("Could not import " + path, e);
}

Silent failures are some of the most expensive bugs to track down. See checked vs unchecked exceptions.

6. Write comments that explain why, not what

// Bad: repeats the code
i++; // increment i

// Good: explains a decision the code can't
// The provider rejects amounts with more than 2 decimal places, so round before sending.
amount = amount.setScale(2, RoundingMode.HALF_EVEN);

Good code explains what it does through its names and structure. Comments are for why.

Tools that help

You do not have to do it all by memory:

  • Your IDE’s refactorings (rename, extract method, extract variable) make cleaning up safe and fast.
  • SonarLint flags code smells as you type. See our list of IntelliJ plugins.
  • Code reviews: ask a colleague to read your code before it is merged. If they have to ask what something does, that is a sign to clean it up.
  • Unit tests let you refactor without fear of breaking things.

The Boy Scout rule

A final idea from Uncle Bob: leave the code cleaner than you found it. You do not have to rewrite everything. Rename one confusing variable, extract one long method, delete one dead comment each time you touch a file. Small improvements add up.

Next time someone reads your code, make sure they can tell that you cared.

Ask a question or leave a comment

Your email address will not be published. Required fields are marked *