Comments and Code Formatting in Java: Clean Code Rules
The comment says seconds. Thread.sleep(long millis) takes milliseconds. This code waits 30 milliseconds, and the comment makes sure nobody notices during review:
private static final int TIMEOUT = 30; // timeout in seconds
// ...
Thread.sleep(TIMEOUT); A name with the unit inside, or a type that carries the unit, cannot drift away from the code the way a comment can:
private static final Duration RETRY_DELAY = Duration.ofSeconds(30);
// ...
Thread.sleep(RETRY_DELAY); // Thread.sleep(Duration) exists since Java 19 Clean comments explain what the code cannot say by itself — why a decision was made, what a public API promises, what will break if you change something. Everything the code can express through names, types and small methods belongs in the code. Formatting is the other half of readability: consistent layout lets the reader see the structure of a class before reading a single line of it.
Don't comment bad code, rewrite it
When you feel the need to explain a piece of code with a comment, first try to make the code explain itself: extract a method with a descriptive name, introduce an explanatory variable or replace a literal with a constant. A comment is the fallback for what cannot be expressed this way.
// Check whether the employee is eligible for full benefits
if (employee.getAge() > 65 && employee.getWorkingYears() > 45) {
// ...
} if (employee.isEligibleForFullBenefits()) {
// ...
}
// in Employee
public boolean isEligibleForFullBenefits() {
return age > RETIREMENT_AGE && workingYears > FULL_BENEFIT_YEARS;
} The comment disappeared, but nothing was lost: the method name says the same thing, it is checked by the compiler on every call, and the rule now lives in one place instead of being copied with the comment into every if that needs it.
Comments worth writing
A good comment carries information that is not in the code: intent, consequences, external constraints and contracts. These comments stay true as long as the reason behind them stays true.
| Kind | Example |
|---|---|
| Explanation of intent (why) | // The bank API rejects amounts with more than 2 decimals, so we round here, not in the UI |
| Warning of consequences | // Not thread-safe: SimpleDateFormat keeps internal state |
| Clarification of an external format | // Matches "2026-12-05T10:15:30Z" (ISO-8601 instant) |
| Javadoc for a public API | /** Returns the order total including tax; never negative. */ |
| TODO with a reference | // TODO(EC-142): remove after all clients use v2 of the API |
| Legal header required by the project | License or copyright text at the top of a file |
Javadoc deserves a special mention: for public classes and methods that other people call, a documentation comment is part of the API. Describe what the method promises (parameters, return value, exceptions, thread safety), not how it is implemented. Tags and the javadoc tool are covered in Javadoc in Java.
A TODO without an owner or a ticket number tends to outlive its author. Most IDEs collect TODOs in a separate view, which only helps if someone looks at it, so link each one to a task that will actually be scheduled.
Comments to delete
Most comments in real projects are noise: they repeat the code, lie about it or keep history that version control already stores. Each of them costs reading time and, sooner or later, becomes wrong.
i++; // increment i
/**
* Sets the name.
* @param name the name
*/
public void setName(String name) { this.name = name; }
// } // end for
// 2019-03-02 Fixed bug with discount (Peter)
// 2019-04-11 Changed rounding (Anna)
// double discount = calculateOldDiscount(order); - Redundant comments say what the code already says. Javadoc on a trivial setter is the same thing in a more formal costume.
- Closing-brace comments such as
// end forare a sign that the block is too long; shorten the method instead. - Journal comments and author/date notes duplicate
git logandgit blame, which are always up to date. Keep an@authortag only if your team requires it. - Commented-out code is the worst of all: nobody dares to delete it, because it looks important. Delete it — the history keeps every old version.
- Mumbling, jokes and messages to colleagues (
// don't touch, it works) belong in the code review or the team chat, not in the source.
Formatting: team rules, not personal taste
The most important formatting rule is consistency: a project should look as if one person wrote it. Which brace style or indentation width you choose matters much less than everybody using the same one.
Agree on a style once, write it down as a formatter configuration (an IntelliJ IDEA code style scheme, an .editorconfig file or a Checkstyle configuration) and commit it to the repository. Then formatting stops being a topic in code reviews, and diffs show real changes instead of whitespace. Widely used starting points are the Google Java Style Guide and the default IntelliJ IDEA style; the original Oracle Code Conventions for Java are from 1999 and are no longer maintained, although most of their rules are still followed.
Vertical formatting: blank lines and ordering
Blank lines separate concepts, and their absence groups lines that belong together. A class without blank lines is a wall of text; a class with a blank line after every statement has no visible structure at all.
public class InvoiceService {
private final InvoiceRepository repository;
private final TaxCalculator taxCalculator;
public InvoiceService(InvoiceRepository repository, TaxCalculator taxCalculator) {
this.repository = repository;
this.taxCalculator = taxCalculator;
}
public Invoice issue(Order order) {
Invoice invoice = createInvoice(order);
repository.save(invoice);
return invoice;
}
private Invoice createInvoice(Order order) {
BigDecimal tax = taxCalculator.taxFor(order);
return new Invoice(order.id(), order.total(), tax);
}
} Related code stays close: a private method sits right below the public method that calls it, so the reader goes down the file instead of jumping around. Variables are declared near their first use, and fields are declared at the top of the class, not scattered between methods. End each file with a single newline and no trailing blank lines; many tools warn about both.
Horizontal formatting: line length, braces, chains
Keep lines short enough to read without horizontal scrolling and to show two files side by side — most current style guides set the limit at 100 or 120 characters. Long expressions are wrapped at operators and dots, with continuation lines indented.
Always use braces for if, else, for and while, even for one statement. Without braces, the next person who adds a second line to the body changes the logic without seeing it:
if (size > 0)
str.append(size + 1);
log.debug("appended"); // runs always, despite the indentation
if (size > 0) {
str.append(size + 1);
log.debug("appended");
} Stream pipelines and builder chains read best with one operation per line, so each step can be read, commented out during debugging and reviewed separately:
List<String> prefixes = strings.stream().filter(s -> s.length() > 2).sorted().map(s -> s.substring(0, 2)).toList();
List<String> prefixes = strings.stream()
.filter(s -> s.length() > 2)
.sorted()
.map(s -> s.substring(0, 2))
.toList(); Let the tools do the formatting
Formatting by hand is a waste of attention. Configure the IDE once and let it do the work: in IntelliJ IDEA, Code → Reformat Code (Ctrl+Alt+L) applies the project style, and Optimize Imports (Ctrl+Alt+O) removes unused imports. The Actions on Save settings can run both automatically.
In a team, add a check to the build so that unformatted code does not reach the main branch: Checkstyle reports violations, while Spotless or the formatter plugins can rewrite the code to the agreed style. Static analysis tools such as SonarLint in the IDE and SonarQube on the server go further and find commented-out code, empty blocks and unused variables, which are covered in the lesson on code smells.
Frequently Asked Questions
Does clean code mean no comments at all?
No. Clean code avoids comments that repeat or excuse the code, but it keeps comments that explain why, warn about consequences and document public APIs with Javadoc. The goal is fewer comments that are always true, not zero comments. More in Comments worth writing.
Should every public method have Javadoc?
Every method of a public API that other teams or library users call should. Inside an application, Javadoc on obvious getters and setters is noise; write it where the contract is not obvious from the name and types, for example which exceptions are thrown or whether null is allowed.
Is it OK to keep commented-out code for later?
No. Version control already keeps every old version, and commented-out code goes stale quickly: it stops compiling, and nobody knows whether it is still needed. Delete it, and mention the commit in the ticket if the code may come back.
What line length should Java code use?
Pick one limit for the project and enforce it with the formatter. The Google Java Style Guide uses 100 characters, many teams use 120. The old Oracle conventions suggested 80, which is tight for modern Java with generics and long names.
Comments