Intermediate 25 min read

Writing Clean Code

By the end of this lesson, you'll be able to:

  • Name variables and methods so their purpose is clear without a comment
  • Recognize when a method is doing too much and should be split up
  • Apply the "read it out loud" test to judge code clarity

Prerequisites: "Branching and Committing Discipline"

Names that explain themselves

// BAD
Integer d = 30;
if (x > d) { ... }

// GOOD
Integer daysOverdue = 30;
if (accountAge > daysOverdue) { ... }

d and x compile identically to daysOverdue and accountAge — but a reader has to guess what d and x mean, while the good version reads almost like English. Clear names are the single cheapest way to make code easier to understand.

A method should do one thing

// BAD: one method doing three unrelated jobs
public void processOrder(Order__c order) {
    // validate the order
    if (order.Total__c <= 0) { return; }
    // calculate tax
    order.Tax__c = order.Total__c * 0.15;
    // send a confirmation email
    Messaging.sendEmail(...);
}

This mirrors the refactor from Module 12's "Review and Refactor" lesson: processOrder is doing validation, calculation, and notification all at once. Splitting it into isValidOrder(), calculateTax(), and sendConfirmation() — each with one clear job — makes each piece independently readable, testable, and reusable.

The "read it out loud" test

if (isEligibleForDiscount(customer) && cartTotal >= minimumForFreeShipping) {
    applyFreeShipping(order);
}

Read that condition out loud: "if the customer is eligible for a discount and the cart total is at least the minimum for free shipping, apply free shipping." It reads like a sentence describing the actual business rule — a strong sign the names and structure are doing their job. If a piece of code makes you stumble reading it aloud, that's usually a sign it needs clearer names or restructuring.

Exercise

Rename the variables in this snippet to clear, self-explanatory names.

Show hint

What do p and t actually represent?

APEX

Writing Clean Code Quiz

1. What is the "read it out loud" test used for?

Log in to submit the quiz and save your score.

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

Clean code is code that's easy for the next person (often you, months later) to read and change safely — a handful of concrete habits make an enormous difference.