Here is what I'm trying to do
First initiate an optional variable, then do procedure A. if procedure A yield null then try procedure B and so on. if all the procedure still yield null, throw exception
#pseudocode
Optional<> someVariable;
if (someVariable is empty):
fetch value through procedure A
assign to someVariable
if (someVariable is empty):
fetch value through procedure B
assign to someVariable
.
.
.
if still empty:
throw exception
The problem is I don't really want to go through procedure B if procedure A already resolve the value and I don't think it is scalable if more procedure is added any input?
With JDK 11 (probably JDK 8+):
public class MyClass {
private Integer procedureA() {
return ...
}
private Integer procedureB() {
return ...
}
...
private final List<Supplier<Integer>> procedures = List.of(
this::procedureA,
this::procedureB,
// ... as many as you want
);
// This code will stay the same, no matter how many procedures you add
public Optional<Integer> readValue() {
Integer someValue = procedures
.stream()
.map( Supplier::get )
.filter( Objects::nonNull )
.findFirst()
.orElseThrow( () -> new RuntimeException( "Exception!" ) );
// I don't think it makes sense to return an optional in this case
// but you can do it if you want to
return Optional.of(someValue);
}
}
This is pretty much the same approach everybody else has suggested, but with the latest Java you can write code that's much more compact and understandable than the one I've seen in the other answers.