Instead of multiple null checks in below case, I am planning to add something readable code instead. May be with the help of java 8 streams/maps. Can somebody help me with this
private String getRailsServiceClass(IRailsComponent railsComponent) {
String serviceClass = "";
if (railsComponent != null && railsComponent.getRailOffer() != null && railsComponent.getRailOffer().getRailProducts().get(0).getRailProduct() != null && railsComponent.getRailOffer().getRailProducts().get(0).getRailProduct().getFareBreakdownList() != null &&
railsComponent.getRailOffer().getRailProducts().get(0).getRailProduct().getFareBreakdownList().get(0).getPassengerFareList() != null && railsComponent.getRailOffer().getRailProducts().get(0).getRailProduct().getFareBreakdownList().get(0).getPassengerFareList().get(0).getPassengerSegmentFareList() != null &&
railsComponent.getRailOffer().getRailProducts().get(0).getRailProduct().getFareBreakdownList().get(0).getPassengerFareList().get(0).getPassengerSegmentFareList().get(0).getCarrierServiceClassDisplayName() != null) {
return railsComponent.getRailOffer().getRailProducts().get(0).getRailProduct().getFareBreakdownList().get(0).getPassengerFareList().get(0).getPassengerSegmentFareList().get(0).getCarrierServiceClassDisplayName();
}
return serviceClass;
}
You can use Optional for your purpose.
String serviceClass = Optional.ofNullable(railsComponent)
.map(IRailsComponent::getRailOffer)
.map(RailOffer::getRailProducts)
...
.orElse("");
Your code is bad because on each check you had to get the items in the lists again and again. That's a lot of I/O to do.
Without using any API (so pre-Java 8 solution) You can clean you code by checking each item one after all (depends on the accessiblity of each class but here is a fully developped condition
RailComponent rc = getRailComponent();
if (rc != null) {
RailOffer ro = rc.getRailOffer()
if (ro != null) {
RailProduct rp = ro.getRailProducts().get(0).getRailProduct();
if (rp != null) {
List<FareBreakDown> fbList = rp.getFareBreakdownList();
if (fbList != null) {
List<PassengerFare> pfList = fb.get(0).getPassengerFareList();
if (pfList != null) {
List<PassengerSegmentFare> psfList = pfList.get(0).getPassengerSegmentFareList();
if (psfList != null) {
String carrierServiceClassDisplayName = psfList.get(0).getCarrierServiceClassDisplayName();
if (carrierServiceClassDisplayName != null) {
return carrierServiceClassDisplayName;
}
}
}
}
}
}
}
You see that's not THAT much of check once you reduce the verbosity of your code
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With