I have three functions. Input and output parameters of all three functions are same.
Let's say
public void String function1(String abc, String xyz);
public void String function2(String abc, String xyz);
public void String function3(String abc, String xyz);
I have a caller function which is implemented like
public void String callerFunction(String abc, String xyz) {
String output = function1(String abc, String xyz);
if(output == null) {
output = function2(String abc, String xyz);
}
if(output == null) {
output = function3(String abc, String xyz);
}
return output;
}
While this code works, what's the best way to write this kind of logic, i may want to add a new function4 also in the future.
One way that comes in my mind is
public interface functionInterface {
public String fetchValue(String abc, String xyz);
}
public class function1Class {
public String fetchValue(String abc, String xyz) {
// return some string.
}
}
public class function2Class {
public String fetchValue(String abc, String xyz) {
// return some string.
}
}
public class function3Class {
public String fetchValue(String abc, String xyz) {
// return some string.
}
}
public void String callerFunction(String abc, String xyz) {
List<functionInterface> flist = new Arraylist<>();
functionInterface f1 = new function1Class();
functionInterface f2 = new function1Class();
functionInterface f3 = new function1Class();
flist.add(f1);
flist.add(f2);
flist.add(f3);
String output = null;
for(functionInterface f : flist) {
output = f.fetchValue(abc, xyz);
if(f.fetchValue(abc, xyz) != null) {
return output;
}
}
return output;
}
- Is this over engineering ?
- Is there a better way to handle this use case ?
Aucun commentaire:
Enregistrer un commentaire