mercredi 7 octobre 2020

How to refactor Java if-else statements?

I am looking to find the best way to refactor this code in Java:

 private boolean parseArguments(String[] args) {
    boolean requestDetails = false;
    for(int i=0; i<args.length; i++) {
        if(args[i].equals("-user") && i+1<args.length) {
            i++;
            username = args[i];
        }
        else if(args[i].equals("-pass") && i+1<args.length) {
            i++;
            password = args[i];
        }
        else if(args[i].equals("-l") && i+1<args.length) {
            i++;
            option.setLanguage(args[i]);
            if(args[i].equals("?")) requestDetails = true;
        }
        else if(args[i].equals("-cl") && i+1<args.length) {
            i++;
            option.setCountryLang(args[i]);
            if(args[i].equals("?")) requestDetails = true;
        }
        else if(args[i].equals("-s")) {
            option.setReadSubdirs(true);
        }
        else if(args[i].equals("-S") && i+1<args.length) {
            i++;
            option.setPathToFiles(args[i]);
        }
        // and many more of them!
        // . . . . . . . . . . .
        // . . . . . . . . . . .
     }
   }

Should I use a design pattern for this? Please help me understanding this, I have a lot of files like that, so I will be able so solve all of them.

Aucun commentaire:

Enregistrer un commentaire