I have the following code, like a git command line system with various supported parameters and commands. But as can be seen, it involves a lot of if-else conditions which
It doesn't seem that clean and is error-prone. Could there be a way to restructure it using some design pattern
public static void main(String... args) {
String firstParam;
try {
firstParam = args[0];
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Please enter a command.");
return;
}
String secondParam = null; String thirdParam = null; String fourthParam = null;
if (args.length > 1) {
secondParam = args[1];
}
if (args.length > 2) {
thirdParam = args[2];
}
if (args.length > 3) {
fourthParam = args[3];
}
git git = new git();
if (firstParam.equals("init")) {
git.init();
} else if (!git.getWorkingdirectory().exists()) {
System.out.println("not initialized");
} else if (firstParam.equals("status")) {
git.status();
} else if (firstParam.equals("log")) {
git.log();
} else if (firstParam.equals("global-log")) {
git.globalLog();
}
else if (secondParam == null) {
System.out.println("Incorreerands.");
} else if (firstParam.equals("add")) {
git.add(secondParam);
} else if (firstParam.equals("rm")) {
Reasoning:
The first thing that comes to my mind is making a class out of each command. That's probably called command pattern. So there will be a class corresponding to - add, rm, status, log, etc.. all the supported arguments to the git command. I am planning to include around 13 such git commands to be specified as a command-line option. That will be like 13 classes.
Not sure if that is a good approach, or could there be any other approach?
Aucun commentaire:
Enregistrer un commentaire