1

switch statements are very good when we have switch cases till 5 but in our case we have 15 switch cases.

I want to know what is best alternate choice for switch statements in java

private OpwaardernId getOpwaardernId(String opId) {

    OpwaardernId opwaardernId;
    switch (opId) {
        case "ID001":
            opwaardernId = opwaardernId.of("xxx");
            break;
        case "ID002":
            opwaardernId = opwaardernId.of("123");
            break;
        case "ID002":
            opwaardernId = opwaardernId.of("abc");
            break;
        case "ID003":
            opwaardernId = opwaardernId.of("asd");
            break;
        case "ID004":
            opwaardernId = opwaardernId.of("rrr");
            break;
        case "ID005":
            opwaardernId = opwaardernId.of("ttt");
            break;
                ...
        case "ID015":
            opwaardernId = opwaardernId.of("aaa");
            break;

        default:
            opwaardernId = null;

    }
    return opwaardernId;
}
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
Anderson
  • 1,100
  • 2
  • 13
  • 17
  • 1
    Maybe use a hashmap? – ernest_k Nov 25 '19 at 14:18
  • so, what wrong with using `switch`? – AterLux Nov 25 '19 at 14:19
  • @ AterLux - having 15-20 switch case is not correct way of handling. It may be performance issue. If I pass a ID that match with last switch, it would have executed all the switch cases – Anderson Nov 25 '19 at 14:22
  • @Anderson, no it would not. It is not the same as series of `if`s. The code will jump directly on the case you needed, with may be small overhead of binary search if values are too sparse. When `switch` with `String`s is used, fird hash value of string is calculated, then `switch` is performed over it, and then strings are compared. But in your case using map may be preferable, but only if it is a static map. Recreating the map on each function call (as in the answer given) will significantly drop performance. – AterLux Nov 26 '19 at 15:26

1 Answers1

6

You can use a Map for example :

private OpwaardernId getOpwaardernId(String opId) {
    // store all value in a map
    Map<String, String> map = Map.of("ID001", "xxx", "ID002", "123", ..);
    // then just call 
    return map.containsKey(opId) ? opwaardernId.of(map.get(opId)) : null;
}
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140