IMHO, the best option is to return an Optional<RollingStock>
, like the foillowing:
public Optional<RollingStock> getHeadPoint() {
if (!train.isEmpty()) {
// or even Optional.ofNullable, if you are not sure
// whether train.get(0) is null or not
return Optional.of(train.get(0));
} else {
return Optional.empty();
}
}
Assuming train
is a collection, as an alternative to manual wrapping the value into an Optional
you could use Stream API
:
public Optional<RollingStock> getHeadPoint() {
return train.stream()
.findFirst();
}
In some cases using inline train.stream().findFirst()
may be more preferable than wrapping it into a separate method.
Once you already modified your method getHeadPoint
to return Optional<RollingStock>
you can use it as follows:
// ...
RollingStock headPoint = getHeadPoint().orElse(yourDefaultRollingStock);
// or
RollingStock headPoint = getHeadPoint().orElseGet(aMethodGettingYourDefaultRollingStock());
// or
RollingStock headPoint = getHeadPoint().orElseThrow(() -> new Exception("The train is empty!"));
// or
getHeadPoint().ifPresent(headPoint -> doSomethingWithHeadPoint(headPoint));