Always Use Braces

 class​ BoardComputer {
 
  CruiseControl cruiseControl;
 
 void​ authorize(User user) {
  Objects.requireNonNull(user);
»if​ (user.isUnknown())
  cruiseControl.logUnauthorizedAccessAttempt();
»if​ (user.isAstronaut())
  cruiseControl.grantAccess(user);
»if​ (user.isCommander())
  cruiseControl.grantAccess(user);
  cruiseControl.grantAdminAccess(user);
  }
 }

Here we’ve translated the switch statement from the previous comparison into separate if statements. There’s one problem, though. The indentation in the snippet is perilously misleading. There are no curly braces after the if, so the condition applies only to the subsequent line. That makes the whole method behave maliciously—the line cruiseControl.grantAdminAccess(user); ...

Get Java By Comparison now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.