Simplify Boolean Expressions

 class​ SpaceShip {
 
  Crew crew;
  FuelTank fuelTank;
  Hull hull;
  Navigator navigator;
  OxygenTank oxygenTank;
 
 boolean​ willCrewSurvive() {
»return​ hull.holes == 0 &&
  fuelTank.fuel >= navigator.requiredFuelToEarth() &&
  oxygenTank.lastsFor(crew.size) > navigator.timeToEarth();
  }
 }

Boolean expressions that combine multiple conditions are often hard to understand and easy to get wrong. But you can make them easier with a few simple tricks.

As in the previous comparison, you can see an example of a validation method. The condition is more complex than the previous one, but it’s already condensed in a single return statement according to Return Boolean Expressions Directly.

The sheer size of the ...

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.