Four Java Bugs That Bad Indentation Hides in Plain Sight
javac does not care what your code looks like. Whitespace carries zero meaning in the Java Language Specification, so the compiler reads your file as a stream of tokens and skips every space you typed. Fine for the machine. A problem for you, because indentation is the part of the code that talks to humans. When the layout says one thing and the braces say another, the reader trusts the layout,…
Java does not consider whitespace when compiling code, so indentation holds no meaning for the compiler. This can lead to bugs, as layout talks to humans while braces convey the intended structure to the machine. Here are four such bugs that hide in plain sight due to incorrect indentation.
The first bug arises when an extra semicolon is added after a condition in an if statement. For example, if (cart.total() FREE_SHIPPING_MIN); appliesFreeShipping(cart); chargeCustomer(cart); The layout suggests carts above a threshold get free shipping, but the semicolon ends the condition, causing applyFreeShipping to run for every order, regardless of the total.
Another bug involves a dangling else that binds to the wrong if statement. With if (customer.isVip()) if (order.isGiftWrapped()) includeGiftCard(order); else chargeUpgradeFee(order); Java assumes else goes with the nearest if, so upgrade fees are charged to VIP customers without gift wrap. To make this intent clear, use braces: if (customer.isVip()) { if (order.isGiftWrapped()) includeGiftCard(order); else chargeUpgradeFee(order); }
A third bug occurs when a closing brace ends the block prematurely. With if (!response.isOk()) { log.warn(bad response, will retry); } retry(request); The indentation suggests both log and retry follow a failure. However, the brace after log closes if, meaning retry occurs on every request, success or failure. Proper formatting reveals this bug immediately.
Lastly, the unbraced guard chain can introduce subtle errors. Consider if (session == null) return false; if (!session.signatureValid()) return false; revokeSession(session.userId()); return grantAccess(session); The first two lines appear as part of a chain, but revokeSession belongs to no if, so it runs for every login, even successful ones, leading to a security issue. Proper use of braces isolates each conditional path and prevents such mistakes.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.