A
A
Alex2015-11-07 00:34:08
Programming
Alex, 2015-11-07 00:34:08

How to implement a console command handler in an application?

Hello! It is necessary to implement command processing in the console application. The user enters a command into the console, it is read using Console.ReadLine() and should be executed by the program itself. The command can contain parameters (separated by a space). Googled, only implementation examples come across through switch..case., i.e.:

string command=Console.ReadLine();
switch (command) {
  case "Команда":
  {
   Действие();
   break;
  }
}

Here questions immediately arise: How to accept a command with parameters? And how correct is this approach? (It seems to me that it is unlikely that developers of large console applications, in which there may be a hundred commands in each, will prescribe 100 cases in the code). Then, maybe there is some other processing method?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexey Pavlov, 2015-11-07
@lexxpavlov

Separate the string by space - this way you will get the command name and parameters, in the first element of the array - the command name, in the rest - parameters. Each parameter must be separated by the symbol "=" - and you will get the parameter name and value.
Next, it's good to create an interface (and/or abstract class) of the command handler and implement the interface for each command. This will give you multiple classes, one for each team. It remains to select the desired handler, and run it, specifying its parameters. If there are a lot of teams, then you can think about further dividing the handler classes into subgroups.
If necessary, I can show an example code for my method. And for good, use the ready-made code (however, see if that someone else's code can parse from a string, and not from the input arguments of the program).

R
Rsa97, 2015-11-07
@Rsa97

It all depends on the level of complexity of these commands. If there are one or two tokens, then string comparison is enough, if the commands are complex, you can write a small lexer and a state machine that processes commands.

R
Rasim Keita, 2015-11-09
@keyros

Read about the command pattern or the query pattern - the answer
of the code example, then you can get a string from the console, parse it with a regular expression and incur request processing

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question