Home » Java » java – How to replace switch-case to OOP-Exceptionshub

java – How to replace switch-case to OOP-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have methods with which I get data from a database.
Depending on the variable that the user entered through the console, I must execute the desired method

       while (flag) {
           try {
               sw = new ScannerWrapper();
               menuHeader();
               int choice = sw.readInt();
               switch (choice) {
                   case 1:
                       System.out.println("Input first name: ");
                       String name = sw.readLine().toUpperCase();
                       printResults(DataParser.getFilmByName(name));
                       break;
                     case 0:
                       System.out.println("Bye-bye. Come again");
                       flag = false;
                       break;
                   default:
                       System.out.println("Please enter correct number");
               }
           } catch (Exception e) {
               System.out.println("Enter correct data");
           } finally {
               DBConnector.getInstance().closeConnection();
           }
       }

This code is very bad.There are more than 5 cases with methods and the code becomes redundant

How to&Answers:

You should have a look at the Strategy design pattern. That will allow you to abstract the logic related to an action.

On top of that, you want to replace the switch to find the right strategy according to the input variable. That is the job of the Factory design pattern, which in your case would return one of the different strategies according to the database value.

Basically:

interface UserAction { 
    public void execute();
}

class ListMovies implements UserAction { 
    public void execute() {
        // List the movies
    }
}

class ExitProgram implements UserAction { 
    public void execute() {
        // Kill kenny
    }
}

class Noop implements UserAction { 
    public void execute() {
        // Do nothing
    }
}

And a factory:

class UserActionFactory {
    public UserAction make(int actionId) {
        switch (actionId) {
            0: return new ListMovies();
            1: return new ExitProgram();
            default: return new Noop();
        }
    }
}

Which then allows:

UserActionFactory factory = new UserActionFactory();
ScannerWrapper sw = new ScannerWrapper();

while (true) {
    menuHeader();
    int choice = sw.readInt();
    UserAction action = factory.make(choice);
    action.execute();

}

This could also be the Command design pattern, depends on how you name things and instantiate objects for the rest of the classes.