Avoid Switch Fallthrough

 class​ BoardComputer {
 
  CruiseControl cruiseControl;
 
 void​ authorize(User user) {
  Objects.requireNonNull(user);
 switch​ (user.getRank()) {
 case​ UNKNOWN:
» cruiseControl.logUnauthorizedAccessAttempt();
 case​ ASTRONAUT:
  cruiseControl.grantAccess(user);
 break​;
 case​ COMMANDER:
  cruiseControl.grantAccess(user);
  cruiseControl.grantAdminAccess(user);
 break​;
  }
  }
 }

Some programming language constructs are infamous because of all the bugs they’ve caused over the years. One of them is the switch, and you should be careful when you use it.

The method authorizeUser() you see here validates its parameters and checks for a null reference. It uses Objects.requireNonNull(), a handy parameter ...

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.