I want to write an apps that accepts user command. The user command is used in this format:
command -parameter
For example, the app can have "Copy", "Paste", "Delete" command I am thinking the program should work like this :
public static void main(String args[]){
if(args[0].equalsIgnoreCase("COPY")){
//handle the copy command
} else if(args[0].equalsIgnoreCase("PASTE")){
//handle the copy command
}/**
code skipped
**/
}
So, it works, but I think it will become more and more complex when I have more command in my program, also, it is different to read. Any ideas to simply the logic?
Simplifying logic circuits is a predominant task when designing a digital system in which you're able to place more functionality on integrated circuits, such as microprocessors. Also, the simpler your circuits are, the less power they consume. Logic functions can be presented in different forms.
If you are concerned about handling the command line parameters then Commons CLI is meant for this.
Go through the CommandLineParser
and if you are concerned about the complexity of your if-else then you can use Command Pattern
public interface Command {
void exec();
}
public class Copy implements Command {
void exec() {
// your copy Code
}
}
public class Paste implements Command {
void exec() {
// your Paste Code
}
}
public class Delete implements Command {
void exec() {
// your Delete Code
}
-- then
public static void main(String args[]){
Map commandMap<String,Command> = new HashMap<String,Command>();
commandMap.put("Copy", new Copy());
commandMap.put("Paste", new Paste());
commandMap.put("Delete", new Delete());
if ( commandMap.containsKey(args[0]) ){
commandMap.get(args[0]).exec();
}
}
Depending on how simple your command line syntax is, a simple enum
may be your solution
public enum Command {
COPY {
@Override void execute() {
System.out.println("Copying...");
}
},
PASTE {
@Override void execute() {
System.out.println("Pasting...");
}
},
DELETE {
@Override void execute() {
System.out.println("Deleting...");
}
},
;
abstract void execute();
public static void main(String args[]) {
Command c = Command.valueOf(args[0].toUpperCase());
c.execute();
}
}
Compile and run this with java Command paste
, java Command bleh
, etc. You'll want to pass the rest of args
to the enum in your production code. Also, valueOf
throws IllegalArgumentException
if no enum constant is found with the specified name.
If your syntax grows to be more complex, though, you may want to use libraries specifically designed for command line parsing, e.g. Apache Commons CLI.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With