How to structure reading of commands given at a(n interactive) CLI prompt?
- by Anto
Let's say I have a program called theprogram (the marketing team was on strike when the product was to be named). I start that program by typing, perhaps not surprisingly, the program name as a command into a command prompt. After that, I get into a loop (from the users standpoint, an interactive command-line prompt), where one command will be read from the user, and depending on what command was given, the program will execute some instructions.
I have been doing something like the following (in C-like pseudocode):
main_loop{
in=read_input();
if(in=="command 1")
do_something();
else if(in=="command 2")
do_something_else();
...
}
(In a real program, I would probably encapsulate more things into different procedures, this is just an example.)
This works well for a small amount of commands, but let's say you have 100, 1000 or even 10 000 of them (the manual would be huge!). It is clearly a bad idea to have 10 000 ifs and else ifs after each other, for instance, the program would be hard to read, hard to maintain, contain a lot of boilerplate code... Yeah, you don't want to do that, so what approach would you recommend me to use (I will probably never use 10 000 commands in a program, but the solution should, at least preferably, be able to scale to that kind of massive (?) problems. The solution doesn't have to allow for arguments to the commands)?