step 6 / 32 · 5 min
The reader is the constraint
Code is read far more often than it is written, and the reader is usually you, months later, with no memory of why.
Naming
int d; // what?
int elapsedDays; // clear
List<User> getUsers() // all of them? from where?
List<User> findActiveUsersInRegion(Region r)The rule worth applying: a name should let a reader skip the body. If they must read the implementation to know what it returns, the name failed.
Short names are fine where the scope is short. i in a three line loop is clear; i as a field is not.
Functions
The useful limit is not a line count but a level of abstraction. A function should do things that all sit at the same level:
public void placeOrder(Order order) {
validate(order);
reserveStock(order);
charge(order);
confirm(order);
}Four names, no detail, and a reader understands the flow in seconds. Each of those then handles one thing.
A function mixing levels, HTTP parsing next to tax arithmetic next to SQL, is hard to read because the reader keeps changing altitude.
Comments say why
// increment i
i++; // noise
// The provider returns 200 with an empty body on a soft failure,
// which is not documented. Treating it as success loses payments.
if (response.body().isEmpty()) retry(); // worth its spaceThe code already says what. A comment earns its place when it explains a decision, a constraint, or something surprising that looks like a mistake.
A comment that repeats the code goes stale and then lies, which is worse than having none.
Nesting
if (user != null) {
if (user.isActive()) {
if (user.hasPermission(p)) {
// the actual work, four levels deepGuard clauses flatten it:
if (user == null) return;
if (!user.isActive()) return;
if (!user.hasPermission(p)) return;
// the actual workEach precondition is handled and dismissed, and the main path is at the left margin where it belongs.
Consistency beats preference
Tabs or spaces, brace placement, naming conventions: pick what the codebase already does. A file written in a personal style is harder to read than one written in a style you dislike but recognise everywhere.
Automate it. A formatter removes the entire category from code review, and arguing about formatting in a review is time not spent on whether the code is correct.