Reputation: 1
I have the necessity to execute some functions based on a particular CLI combination options (I use the Apache Commons CLI library).
myprogram -a -b ptionArgument -c
myprogram -a -c
myprogram -d optionArgument1 optionArgument2
To manage this situation, I have a very long list of "else if" based on a particular combination, all in my main function:
if (line.hasOption('a') && line.hasOption('b') && line.hasOption('c')){
method1();
method2();
}
else if (line.hasOption('a') && line.hasOption('c')){
method4();
}
else if (line.hasOption('d')){
method1();
method4();
}
....
Is there a better way to design this? (by using some design pattern for example).
Upvotes: 0
Views: 248
Reputation: 319
I would come up with this creating CombinationHandler
interface with handle()
method and creating Map, where arguments is the key and CombinationHandler
's are values.
After that you can simply add different combinations of CombinationHandler
's to each argument combination and invoke them
interface CombinationHandler {
void handle();
// or declare other method signatures
}
public class CombinationComposer {
/* key is a merged combination of arguments*/
private Map<String, List<CombinationHandler>> handlingStrategies = new HashMap<>();
public void execute(String arguments) {
handlingStrategies.getOrDefault(arguments, new ArrayList<>())
.forEach(CombinationHandler::handle);
}
public CombinationComposer() {
handlingStrategies.put("abc", Lists.asList(
() -> System.out.println(1),
() -> System.out.println(2))
);
}
}
public static void main(String[] args) {
String argsString; //squashing array
new CombinationComposer().execute(argsString);
}
Upvotes: 1