Clean Methods in Java: Small, One Job, Few Parameters
Call getSalary(true) twice on the same employee and you get two different answers:
public class Employee {
private double salary = 1000;
public double getSalary(boolean hasBonus) {
if (hasBonus) {
salary += 100;
}
return salary;
}
}
Employee employee = new Employee();
System.out.println(employee.getSalary(true));
System.out.println(employee.getSalary(true));
System.out.println(employee.getSalary(false)); 1100.0
1200.0
1200.0 The method looks like a getter, takes a flag that switches it between two behaviors and changes the object while answering a question. Three rules of clean methods are broken in five lines, and the bug is invisible at the call site.
Clean methods are small methods that do one thing, work at one level of abstraction, have no hidden side effects and take as few parameters as possible. The name of such a method tells the whole story, so a reader can trust a call without opening the body. In Java the same rules apply to static and instance methods, constructors and lambdas.
Keep methods small
A clean method fits on one screen without scrolling, and most methods are much shorter than that — often under 20 lines. There is no magic number in the language, but a short method is easier to name, easier to test and easier to reuse than a long one.
Size also affects blocks inside a method. When the body of an if, else or loop is a single call, the condition and the action both read as plain English:
for (Employee employee : employees) {
payIfNecessary(employee);
} Deep nesting is the clearest signal that a method has grown too big. Two levels of indentation are normal; four levels mean that the inner blocks deserve their own names.
Do one thing
A method does one thing when all its statements serve the single purpose stated in its name, and you cannot extract another method from it without just restating the code. If you can split the body into sections with blank lines and give each section a heading, it does several things.
// Three jobs: validation, persistence, notification
public void register(User user) {
if (user.email() == null || !user.email().contains("@")) {
throw new IllegalArgumentException("Invalid email: " + user.email());
}
if (user.password().length() < 8) {
throw new IllegalArgumentException("Password is too short");
}
repository.save(user);
mailer.send(user.email(), "Welcome!", "Thanks for signing up.");
} // One job: coordinate the registration steps
public void register(User user) {
validate(user);
repository.save(user);
sendWelcomeEmail(user);
} The second version still has four lines, but each line is a step of the same story. The details moved to validate and sendWelcomeEmail, which can be read, tested and changed separately.
One level of abstraction per method
All statements of a method should be at the same level of detail. When a high-level step like repository.save(user) sits next to low-level string manipulation, the reader cannot tell which lines are the important concepts and which are implementation details.
public String buildReport(List<Order> orders) {
String header = createHeader(); // high level
StringBuilder body = new StringBuilder();
for (Order order : orders) { // low level
body.append(order.id()).append(';')
.append(String.format("%.2f", order.total())).append('\n');
}
return header + body + createFooter(orders); // high level
} Move the loop into formatOrders(orders) and the method becomes three statements at one level. Code then reads top-down like a newspaper article: each method is followed by the methods it calls, one level of detail lower. This ordering is sometimes called the stepdown rule.
No hidden side effects
A side effect is any change that the method makes beyond what its name promises: modifying a field, a parameter, a global state or the outside world. Side effects are not bad in themselves — saving data is the purpose of save() — but a hidden one breaks the reader’s trust in the name.
public boolean checkPassword(String userName, String password) {
String stored = passwordStore.findHash(userName);
if (stored != null && stored.equals(hash(password))) {
Session.initialize(); // hidden side effect
return true;
}
return false;
} The name says «check», so a developer will happily call it to re-validate the password before changing an email — and silently reset the user’s current session. Either rename the method to what it really does (checkPasswordAndInitializeSession, which immediately shows that it does two things) or, better, remove the session call and let the login flow do it explicitly.
Output parameters are a related trap. A call like appendFooter(report) makes the reader wonder whether report is an input or a target. If a method must change the state of an object, make it a method of that object: report.appendFooter().
Command-query separation
Command-query separation (CQS) means that a method either does something (a command that changes state and returns void) or answers a question (a query that returns a value and changes nothing), but not both. Queries can then be called any number of times, in any order, without surprises.
// What does true mean: "the attribute was set" or "it already had this value"?
if (set("username", "Bob")) { /* ... */ }
// Separate question and command
if (attributeExists("username")) {
setAttribute("username", "Bob");
} The JDK itself breaks CQS in places for good reasons: Iterator.next() returns an element and advances the iterator, Set.add() returns whether the element was added, and Map.put() returns the old value. Treat these as deliberate exceptions for atomic operations, not as a model for business code. In your own classes, a getter that modifies the object, like getSalary(true) at the top of this lesson, is always a defect.
How many parameters is too many
The ideal number of method parameters is zero, one or two; three needs a reason, and more than three should be packed into an object. Every parameter is something the reader must keep in mind and something a test must cover in combination with all the others.
| Arity | Example | Comment |
|---|---|---|
| Niladic (0) | order.total() | Easiest to read and to test |
| Monadic (1) | fileExists(name), openFile(name) | Fine when the form is one of the three common ones (below) |
| Dyadic (2) | new Point(x, y), assertEquals(expected, actual) | Fine when the two values are naturally ordered; otherwise the order is easy to mix up |
| Triadic (3) | assertEquals(message, expected, actual) | Order mistakes become common; consider an object |
| Polyadic (4+) | makeCircle(x, y, radius, color, filled) | Group related values into a parameter object |
A method with one argument usually has one of three common forms, and the name should make the form obvious:
- Question about the argument:
boolean fileExists(String fileName)— the shape of aPredicate. - Transformation of the argument into something else:
InputStream openFile(String fileName)— the shape of aFunction. - Event: the argument is used to change the state of the system, nothing is returned:
void passwordAttemptFailedNtimes(int attempts)— the shape of aConsumer.
Anything else confuses the reader. void includeSetupPageInto(StringBuilder pageText) transforms its argument but returns nothing, so the result hides in the parameter; StringBuilder transform(StringBuilder in) at least returns the result, but the caller still cannot tell whether the input was modified too.
Flag arguments
A flag argument is a boolean parameter that selects between two behaviors inside the method. It announces that the method does more than one thing, and at the call site render(true) means nothing until you open the declaration.
The fix is to split the method so that each branch gets its own name. For the employee from the start of the lesson, the bonus becomes a separate query and the getter stops mutating the object; a record makes accidental mutation impossible:
public record Employee(double salary, boolean bonusEligible) {
private static final double BONUS = 100;
public double bonus() {
return bonusEligible ? BONUS : 0;
}
public double totalIncome() {
return salary + bonus();
}
}
Employee employee = new Employee(1000, true);
System.out.println(employee.totalIncome());
System.out.println(employee.totalIncome());
System.out.println(employee.salary()); 1100.0
1100.0
1000.0 The same applies to flags in your own APIs: instead of printInvoice(invoice, true) write printInvoiceAsPdf(invoice) and printInvoiceAsText(invoice). If there are more than two variants, an enum parameter such as Format.PDF is clearer than several booleans.
Parameter objects and records
When several parameters always travel together, they are a concept that deserves a name. Grouping them into a parameter object shortens the signature, removes order mistakes and gives a natural home to validation.
// Which double is the radius?
Circle makeCircle(double x, double y, double radius) { /* ... */ }
// The concept "point" now has a name
record Point(double x, double y) {}
Circle makeCircle(Point center, double radius) { /* ... */ } Before Java 16 a parameter object meant a class with a constructor, getters, equals and hashCode, which was often enough to put developers off. A record is a one-line declaration, so there is no longer a cost argument against it. A record can also validate its components in a compact constructor, so an invalid DateRange with the end before the start cannot even be created. More about records is in Java Records.
Varargs (String... names) count as one parameter when all values are treated the same way, as in String.format(pattern, args...). If the values play different roles, they are not a list and need names.
Frequently Asked Questions
How many lines should a Java method have?
There is no rule in the language. A practical target is a method you can read without scrolling, and most methods in clean code are under 20 lines. Length is a symptom: a method that does one thing at one level of abstraction rarely grows long. More in Keep methods small.
Don't many small methods make the code harder to follow?
Only when they are badly named or scattered. If each method has a precise name and the methods are ordered top-down, the reader can stop at the level of detail they need and does not have to jump. A few calls with clear names are easier to follow than one 200-line method.
Is a boolean parameter always a code smell?
No. A boolean that is data, such as setVisible(boolean visible) or the record component bonusEligible, is fine. The smell is a boolean that switches the method between two different algorithms. Split such a method in two or replace the flag with an enum when there are more than two variants.
Does Iterator.next() violate command-query separation?
Yes, strictly speaking: it returns an element and moves the iterator forward. The JDK makes this trade-off on purpose, because reading and advancing must happen together. In business code keep queries free of side effects and treat such methods as rare, documented exceptions.
Practice
Reinforce this lesson with hands-on tasks, each with a level and a time estimate.
- Split a Report Method with a Flag Argument
- Extract Methods from a Reminder Loop and Make It Testable
- Separate the Command from the Query in an Inventory
- Replace StringBuilder Plumbing with a Small HtmlTag Class
Comments