Search code examples
javalistexceptionswitch-statementcontains

How to improve switch case that returns true/false or throw an exception?


Given the following code:

private boolean isBlahTrue(final BigDecimal status) {

        switch (status.intValue()) {

            case 1:
            case 2:
            case 3:
                return true;

            case 5:
            case 6:
            case 7:
                return false;

            default:
                throw new MyAppRuntimeException("Status unknown!");
        }
    }

My question is: Is this good or bad practice?

Logic is:

1, 2, 3  --> true
5, 6, 7  --> false

But anyway one could think about that a simple IF would do the stuff too, like

if (1,2,3) {true}, else {false}

.

But then I would not check if the status is e.g. 4 (which must lead to an exception).

I tried some solutions, like contains, but the code doesn't improve.

Any ideas that I could try?


Solution

  • I would suggest using a Map in this case.

    something like

    Map<Integer, Boolean> statusChecker = new HashMap<>();
    statusChecker.put(1, true);
    statusChecker.put(2, true);
    ... 
    statusChecker.put(5, false);
    ...
    

    Now you can do the checking

    if(!statusChecker.contains(status)) {
       throw RuntimeException("invalid status");
    } else {
       return statusChecker.get(status);
    }