In a JSF application I have some methods with multiple return points as the following:
public String Method1() {
...
if (condition1) {
elaborate1();
return "Case1";
}
if (condition2) {
elaborate2();
return "Case2";
}
if (condition3) {
elaborate3();
return "Case3";
}
...
}
The conditions and consequent elaborations are common to more methods, and I would like to write them only once. Unfortunately, it is not easy to refactor due to the multiple return points.
I'm not comfortable with functional interfaces, but I hope I could use them to refactor the code above. My idea is to write something like this:
String elaboration1 ( T NextElaborations) {
if (condition1) {
elaborate1();
return "Case1";
}
return NextElaborations.get();
}
Is it possible ? I'm stuck, most examples on internet use lambdas and not methods.
Update 1 @Alexander Ivanchenko I need to study the links you provided before evaluating your answer, I'm not familiar with streams.
After posting the question I made some practice with Functional interfaces and ended up with the following pseudo java code:
@FunctionalInterface
public interface MethodComposition {
String Execute(Supplier<String> supplier)
}
...
String FinalStep() {
FinalElaboration();
return "finalResult";
}
String ElaborationX(Supplier<String> supplier) {
if (conditionX) {
elaborationX();
return "ResultX";
}
return supplier.get();
}
...
public String Method1() {
Supplier<String> finalSupplier = this::FinalStep;
MethodComposition stepX = this::ElaborationX;
...
return step1.Execute(() ->
step2.Execute(() ->
...
stepN.Execute(finalSupplier)));
}
Despite the ugly syntax it is quite close to what I wanted, I would need more flexibility because ElaborationX() is very similar but not equal in Method1 and Method_N.