Clean code: naming, methods and refactoring
Habits that make code easy to read and change:
- Names say what, not how:
activeStudents, notlist2;calculateGst(amount), notcalc(a). Booleans read as questions:isPaid,hasAccess. - Small methods that do one thing, at one level of detail. If a block needs a comment to explain it, extract a well-named method instead.
- Few parameters: more than three usually means a missing object, such as a
DateRangerecord. - Return early instead of nesting ifs five levels deep.
- No magic numbers:
MAX_ATTEMPTS = 3instead of a bare 3. - Comments explain why, not what the code already says.
- Leave it cleaner than you found it: small refactors, backed by tests, keep code healthy.
Your IDE refactors safely: rename (Shift+F6 in IntelliJ), extract method (Ctrl+Alt+M), inline, and introduce variable.
Old way vs new way
public double calc(List<Object[]> l, int t) {
double r = 0;
for (Object[] o : l) {
if (o[2].equals("PAID")) {
if ((int) o[1] > 0) {
if (t == 1) {
r = r + (double) o[3] * 1.18;
} else {
r = r + (double) o[3];
}
}
}
}
return r;
}public record Order(String id, int items, Status status, BigDecimal amount) {
boolean isPaid() { return status == Status.PAID && items > 0; }
}
private static final BigDecimal GST_RATE = new BigDecimal("0.18");
public BigDecimal paidRevenue(List<Order> orders, boolean includeGst) {
BigDecimal net = orders.stream()
.filter(Order::isPaid)
.map(Order::amount)
.reduce(BigDecimal.ZERO, BigDecimal::add);
return includeGst ? withGst(net) : net;
}
private BigDecimal withGst(BigDecimal amount) {
return amount.add(amount.multiply(GST_RATE));
}Common mistake
Writing comments that repeat the code, like i++ // increment i. They add noise and go stale; name things well and comment the reasons.
Under the hood
Consistency beats personal taste: agree on formatting (a shared formatter such as google-java-format or common IDE settings), naming and package structure as a team, and enforce them in CI. Static analysis tools (SonarQube, SpotBugs, Error Prone) catch bugs and code smells automatically. Refactor with tests in place; without them, cleaning up is just risky editing.
Check yourself
Which is the best name for a boolean?
How this connects
Know these first
Where this leads
Part of Java from zero.
Was this lesson helpful?
Finished reading? Mark it complete to track your progress.