dimanche 3 mars 2019

React to console inputs (commands) - how to handle multiple options most efficient?

Some information (don't want to confuse you with a lot of shitty code):

I've done a pretty large console programm (my largest project so far) which helps me a lot with managing some accounts / assets and more. I'm constantly adding more features but at the same time I reshape the code to work on my shitty coding style.

The console program has a lot of commands the user can type and for every command different methods get called / objects get created / manipulated and so on.

My keywords which are saved in an ArrayList<String> and my commands have this type: [keyword] [...n more Strings]

DESIGN PROBLEM 1:

I have a method cmdProcessor(String[] arguments) which handles the input (command) of the user, and the [keyword] is always the first argument arguments[0]. That means I have a large number of if-statements of this type: if(arguments[0].equalsIgnoreCase("keyword") callMethod(argmts); where in the String[] argmts the remaining arguments[1] ... [n] are.

  • Is this a good way to handle this or should I go with switch-case?
  • Or something else (what?)? Is it better to save the keywords in a HashMap<String, Method>?

DESIGN PROBLEM 2:

The methods (see above callMethod(argmts) ), which are triggered by the entered keyword look even more chaotic. Since the same method can have different numbers and forms of arguments saved in the String[] argmts the method is full of if(argmts.length == ...) to check length, and every of these if-blocks has a bunch of switch-case options which also have a lot of ifs and so on. The last else and the default-case in switch-case I always use for error-handling (throwing error codes and and explanation why the pattern doesn't match and so on).

  • Is this good or are there better ways?
  • I thought about using lots of submethods, which would also blow up my program and cost a lot of time but maybe improve readability / overview. Is this okay, or what is the best option in such cases (lots of ifs and switch-case)?

Since I want to build more and more around this program maybe I should start now to fix bad design before it's too late. :)

Aucun commentaire:

Enregistrer un commentaire