Skip to content
javahacks.dev
Architecture

Clean Code in Java Rules That Hold Up in Real Codebases

A short list of clean code rules for Java that survive contact with real projects: naming, small methods, immutability, exceptions and when to ignore a rule.

6 min read
Summarize in AI
Flat illustration of a list, a set and a map, with the OpenJDK, IntelliJ IDEA and Kotlin logos.

Clean code advice has a bad reputation because it is often given as commandments. The rules below come from what makes a Java codebase easier to change, and each one comes with the case where it stops helping. They apply to Java 25 style code, with records and sealed types where relevant, which are covered in the modern Java guide.

1. Name for meaning

java
// before
List<Order> l = repo.f(c, 30);

// after
List<Order> recentOrders = orders.findByCustomerSince(customer, Duration.ofDays(30));

A name is documentation that cannot go stale. Use nouns for values, verbs for actions and the domain's own words. Avoid abbreviations except those everyone knows (id, url). A long name is fine; a name that needs a comment is not. Rename freely: the IDE does it safely.

2. Keep methods at one level of abstraction

A method that parses input, validates it, applies pricing and writes to the database mixes levels. Split by what, not by length:

java
Order place(CreateOrder request) {
    validate(request);
    Order order = pricing.priceOf(request);
    return orders.save(order);
}

The top method reads as a story, and each helper holds the detail. There is no magic line count; 15 to 20 lines is a hint that a method does several things, and a 40-line method that is a clear switch over cases may be fine.

3. Prefer immutable data

java
public record Money(long cents, String currency) {
    public Money {
        Objects.requireNonNull(currency);
        if (cents < 0) throw new IllegalArgumentException("cents must not be negative");
    }
}

An object that cannot change cannot be changed by surprise, can be shared across threads and is safe as a map key. Use records for values, final fields elsewhere and List.copyOf at boundaries. The cost is allocation for each change, which is usually irrelevant. A JPA entity is the common exception, since the framework needs mutable state.

4. Fail fast and clearly

Check arguments where they enter and throw an exception that names the problem:

java
if (quantity <= 0) {
    throw new IllegalArgumentException("quantity must be positive but was " + quantity);
}

A null or a negative number that travels three layers before blowing up is expensive to debug. Do not catch Exception to hide a failure, and do not return null to mean "error". Use exceptions for exceptional cases and Optional or an empty collection for absence. Reading the failures later is the subject of how to read a stack trace.

5. Avoid boolean parameters

render(order, true, false) tells the reader nothing. Replace flags with two methods, an enum or a parameter object:

java
render(order, Format.PDF, Language.FRENCH);

Each flag doubles the paths through a method, and tests must cover them all.

6. Comments explain why

A comment that restates the code (// increment i) is noise that rots. Write comments for decisions that the code cannot show: why this algorithm, why this odd constant, what the external system's quirk is. If you need a comment to explain what a block does, extract a method and name it.

7. Keep classes small and cohesive

A class should have one reason to change; the fuller treatment is in the single responsibility principle. Signs that a class is too big: many unrelated fields, methods that use disjoint subsets of the fields and a name ending in Manager or Util.

8. Depend on abstractions at the edges

Code that creates its collaborators with new cannot be tested in isolation. Pass them in through the constructor, as in dependency injection. Introduce an interface where a second implementation or a test fake is real, and not for every class.

9. Test the behavior, then refactor under it

Refactoring without tests is guessing. Write tests that describe what the code should do, then change the structure. Tests are also the best documentation of intent; see the JUnit 5 handbook.

10. Do not abstract early

Two similar pieces of code are not yet a pattern. Wait for the third, and see what actually varies. A premature abstraction costs more than duplication, because the wrong abstraction is hard to undo.

The rules applied to one real method

Rules read well on slides and fail on contact with a method that has grown for three years. Here is a realistic one:

java
public String process(Map<String, Object> data, boolean notify, boolean fast) {
    String result = null;
    if (data != null) {
        if (data.get("qty") != null && (Integer) data.get("qty") > 0) {
            Object p = data.get("price");
            double t = (p == null ? 0 : (Double) p) * (Integer) data.get("qty");
            if (!fast) {
                t = t - t * discount((String) data.get("cust"));
            }
            repo.save(new Order((String) data.get("cust"), t));
            if (notify) {
                mailer.send((String) data.get("cust"), "Order total " + t);
            }
            result = "OK";
        } else {
            result = "BAD";
        }
    } else {
        result = "BAD";
    }
    return result;
}

Count the problems against the rules: names that say nothing (data, t, p), a map where a type belongs, double for money, two boolean flags, a string result that stands for success or failure, nesting four levels deep, validation, pricing, persistence and notification in one method, and an Object cast the compiler cannot check.

The same behavior, cleaned up in steps

Introduce a type for the input and validate at the edge, which also gives the domain its own words (rules 1 and 4):

java
public record PlaceOrder(String customerId, int quantity, Money unitPrice) {

    public PlaceOrder {
        Objects.requireNonNull(customerId, "customerId");
        Objects.requireNonNull(unitPrice, "unitPrice");
        if (quantity <= 0) {
            throw new IllegalArgumentException("quantity must be positive but was " + quantity);
        }
    }

    Money subtotal() {
        return unitPrice.times(quantity);
    }
}

Replace the boolean flags with what they mean (rule 5) and return a result type instead of a string (rule 4):

java
public enum Pricing { STANDARD, PROMOTIONAL }

public sealed interface OrderResult {
    record Placed(long orderId, Money total) implements OrderResult {}
    record Rejected(String reason) implements OrderResult {}
}

Now the method reads at one level of abstraction (rule 2), with each step a named operation:

java
@Transactional
public OrderResult place(PlaceOrder request, Pricing pricing) {
    Money total = priced(request, pricing);
    Order saved = orders.save(new Order(request.customerId(), total));
    notifications.orderPlaced(saved);
    return new OrderResult.Placed(saved.id(), total);
}

Money priced(PlaceOrder request, Pricing pricing) {
    Money subtotal = request.subtotal();
    return pricing == Pricing.PROMOTIONAL
        ? subtotal
        : subtotal.minus(subtotal.times(discounts.rateFor(request.customerId())));
}

The caller handles the result with a switch that the compiler checks for completeness, so adding a third outcome later fails the build in every place that forgot it:

java
String message = switch (service.place(request, Pricing.STANDARD)) {
    case OrderResult.Placed p -> "Placed " + p.orderId();
    case OrderResult.Rejected r -> "Rejected: " + r.reason();
};

Tests first, so the refactoring is safe

Rule 9 matters most here. Before touching the old method, pin what it does, including the odd cases, with a characterization test:

java
class OrderPricingTest {

    @ParameterizedTest
    @CsvSource({
        "10, 5.00, STANDARD,    47.50",
        "10, 5.00, PROMOTIONAL, 50.00",
        "1,  5.00, STANDARD,    4.75"
    })
    void totals(int quantity, String price, Pricing pricing, String expected) {
        var request = new PlaceOrder("cust-1", quantity, Money.of(price));
        assertEquals(Money.of(expected), service.priced(request, pricing));
    }

    @Test
    void zeroQuantityIsRejectedAtTheEdge() {
        assertThrows(IllegalArgumentException.class,
            () -> new PlaceOrder("cust-1", 0, Money.of("5.00")));
    }
}

The numbers above assume a 5 percent customer discount. The test table is also the specification: a product owner can read it and say which rows are wrong, which is a review the original method could never have had.

What not to extract

The cleaned version has more types, and that is a cost. Resist the urge to go further. A DiscountStrategyFactory with one strategy, an interface with one implementation and no test double, a method extracted whose name restates its body: these add reading cost without adding meaning. A good test for any new abstraction is whether you can write its name without the words "helper", "manager" or "util". If you cannot, the thing has no identity yet, and leaving it inline is the cleaner choice.

When these rules do not apply

Performance-critical inner loops may trade readability for speed after measurement, and generated code and scripts need not follow them. Rules are in service of change: when following one makes the next change harder, ignore it and say why in a comment. The Google Java Style Guide and the Java Language Specification give formatting and syntax references.

Also inJava Core
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.