f.trajkovski
f.trajkovski

Reputation: 825

Avoid repetition of same if case for different cases

I have the following code:

if (product != null) {
    //tryToGetProductFromOnePlace 
}
if (product != null) {
    //tryToGetProductFromSecondPlace 
}
if (product != null) {
    //tryToGetProductFromThirdPlace 
}
if (product != null) {
    //tryToGetProductFromFourthPlace
}
return product;

I want to refactor this code to look better but I have no ideas. I can't use recursion since the logic of getting the product is different all the time. I can't return it in the if case since I need to get the value and only if all these 4 combinations are not ok then to return null. Any suggestion of how to improve the code?

Upvotes: 1

Views: 59

Answers (1)

jacobm
jacobm

Reputation: 14025

You can rewrite your methods to return Optional values instead of null and then chain them using Optional's or method:

return this.tryToGetProductFromOnePlace()
    .or(this::tryToGetProductFromSecondPlace)
    .or(this::tryToGetProductFromThirdPlace)
    .or(this::tryToGetProductFromFourthPlace);

If for some reason you need to preserve the external interface of returning null instead of Optional.empty() for an absent value, you can add .orElse(null) to the end of the call chain.

Upvotes: 2

Related Questions