2

anyone has ideas about making this block of if-else statements simpler other than purely using switch-case statements? Thanks for your time!

public void onButtonClick(int type, int state) { 
        if (type == 1) {
            if (state == 1)                            
                jsonDataToString(); // method 1
            else if (state == 2)
                filterRecordFile(); // method 2
            else if (state == 3)
                filterResourceFile(); // method 3
        } else if (type == 2) { 
            if (state == 1)
                jsonDataToString(); // method 1
            else if (state == 2)
                filterHasBackup(); // method 4
            else if (state == 3)
                filterNotBackup(); // method 5
        } else if (type == 3) { 
            if (state == 1)
                jsonDataToString(); // method 1
            else if (state == 2)
                filterOverSize(); // method 6
            else if (state == 3)
                filterDownSize(); // method 7
        } 
    }
6
  • At first try case step. Then, write case type inside case step statement. Then, you can deal with type Commented Jul 13, 2021 at 6:46
  • Well, you could try a map that takes the type/state combination as a key and a function/supplier/consumer as the value. Then look up the approriate method and execute it if you've found one. That, of course, adds some complexity but can help when combinations are growing in number. Commented Jul 13, 2021 at 6:47
  • @maloomeister look at his code properly. He is executing something else while state is 2 and type is 2. Commented Jul 13, 2021 at 6:48
  • 1
    @Istiak yes, however the comment was about the fact that when state == 1, the same method is executed unrelated to the value of type. Commented Jul 13, 2021 at 6:50
  • 3
    The method being called onButtonClick() looks like you might be using that in action listeners or something like that. If you're assigning the same listener to multiple buttons and just use type and state to distinguish between them then I'd suggest using different listeners instead. Commented Jul 13, 2021 at 6:51

4 Answers 4

1

You can use tabular functions for such handlers. For example:

class Main {
  private static final Runnable[][] HANDLERS_TABLE = {
    { Main::jsonDataToString, Main::filterRecordFile, Main::filterResourceFile },
    { Main::jsonDataToString, Main::filterHasBackup, Main::filterNotBackup }
  };

  private static void jsonDataToString() {
    System.out.println("Hello jsonDataToString!");
  }

  private static void filterRecordFile() {
    System.out.println("Hello filterRecordFile!");
  }

  private static void filterResourceFile() {
    System.out.println("Hello filterResourceFile!");
  }

  private static void filterHasBackup() {
    System.out.println("Hello filterHasBackup!");
  }

  private static void filterNotBackup() {
    System.out.println("Hello filterNotBackup!");
  }

  public static void onButtonClick(int type, int state) { 
    HANDLERS_TABLE[type][state].run();
  }

  public static void main(String[] args) {
    onButtonClick(1, 1);
  }
}

https://replit.com/join/yzjqwikvil-redneckz

Also, it makes sense to use enums for keys. For example:

enum HandlerType {
  FIRST, SECOND
}

public static void onButtonClick(HandlerType type, int state) { 
    HANDLERS_TABLE[type.ordinal()][state].run();
}
Sign up to request clarification or add additional context in comments.

2 Comments

This will run into an ArrayIndexOutOfBoundsException, e.g. when calling onButtonClick(2, 3). You'd have to subtract 1 from the arguments so that you can use them as array indices.
That's why I propose enums. Also you can check input to restrict possible values. It is not a big deal. In the original example, the handler will do nothing silently in case of invalid input ;)
1

If you just want to make your code easier to read, you could try to format it differently by combining both conditions. Although you have to write type == 1 multiple times, it reduces the amount of nested if statements, which makes the code more readable.

public void onButtonClick(int type, int state) { 
    if (type == 1 && state == 1) jsonDataToString();
    if (type == 1 && state == 2) filterRecordFile();                       
    if (type == 1 && state == 3) filterResourceFile();
    if (type == 2 && state == 1) jsonDataToString();
    if (type == 2 && state == 2) filterHasBackup();
    if (type == 2 && state == 3) filterNotBackup();
}

Comments

1

I would factor out the state handling and convert it to switches, like:

public void onButtonClick(int type, int state) {
    if (type == 1) {
        handleTypeOne(state);
    } else if (type == 2) {
        handleTypeTwo(state);
    }
}

private void handleTypeOne(int state) {
    switch(state) {
        case 1:
            jsonDataToString(); // method 1
            break;
        case 2:
            filterRecordFile(); // method 2
            break;
        case 3:
            filterResourceFile(); // method 3
            break;
        default:
            break;
    }
}

private void handleTypeTwo(int state) {
    switch(state) {
        case 1:
            jsonDataToString(); // method 1
            break;
        case 2:
            filterHasBackup(); // method 4
            break;
        case 3:
            filterNotBackup(); // method 5
            break;
        default:
            break;
    }
}

This allows you to choose more meaningful method names than I did. Besides (and unrelated to your question), I would recommend to introduce constants for the state values in order to make the case selections more comprehensible.

Comments

0

thanks for your help. Here I found a great and detailed explanation: https://programmer.help/blogs/java-optimization-28-optimizing-if-else-writing.html

His blog gives 8 optimization schemes to optimize if-else writing. I leave it here for late-comers :-)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.