Implementing equals
Conventional name for return value
Avoid basic style errors
return statements are used, instead of the usual single
point of exit.
This technique can be easily abused, and should be used with care.
It's mainly used to replace nested if structures.
Multiple return statements seem to work well for "guard
code" at the beginning of a method, in which the main body of the method
is executed only if certain conditions are satisfied.
Example
Here, equals has multiple return statements, since
a successful test implies that further comparison is redundant. The alternative
is to use multiple if statements, which some would find less legible.
import java.math.BigDecimal; import java.time.LocalDate; import java.util.List; import java.util.Objects; public final class Automobile { @Override public boolean equals(Object aThat) { if (this == aThat) return true; if (!(aThat instanceof Automobile)) return false; Automobile that = (Automobile)aThat; for(int i = 0; i < this.getSigFields().length; ++i){ if (!Objects.equals(this.getSigFields()[i], that.getSigFields()[i])){ return false; } } return true; } @Override public int hashCode() { return Objects.hash(getSigFields()); } //..elided // PRIVATE private String name; private Integer numDoors; private List<String> options; private BigDecimal gasMileage; private String color; private List<LocalDate> maintenanceChecks; private Object[] getSigFields(){ Object[] result = { name, numDoors, options, gasMileage, color, maintenanceChecks }; return result; } }