The Switch vs. If-then-else statements

I think this detail might be of general interest: The use-case for using the switch statement instead of the if-then-else statement, is a question of readability (preference) - but only in cases where you’re testing expressions based on single values.

Cited:
Deciding whether to use if-then-else statements or a switch statement is based on readability and the expression that the statement is testing. An if-then-else statement can test expressions based on ranges of values or conditions, whereas a switch statement tests expressions based only on a single integer, enumerated value, or String object.

Speaking from a bit of personal experience, the best time to use a switch-case is when handling an enumerated type (especially if you do not control the type to add better polymorphism directly to the type - eg. generated protobuf enums). Many compilers can even tell you if your switch-case is not exhaustive for the enum type which can be very useful for preventing errors.

// Position.java
enum Position { FIRST, SECOND, THIRD }

// somewhere other than the Position.java file
String raceResultMessageFor(String racer, Position position) {
  switch (position) {
    case FIRST: return String.format("Congrats %s, you got 1st place!", racer);
    case SECOND: return String.format("Way to go %s, you got 2nd place!", racer);
    case THIRD: return String.format("Not bad %s, you got 3rd place!", racer);
    // Depending on your compiler you may need a default here...
    // default: throw new IllegalStateException("Unhandled position: " + position);
  }
  // ... or something like this
  // throw new IllegalStateException("Unhandled position: " + position);
}

NOTE: If you do have control over the enum, it may be better to add polymorphism:

enum Position {
  FIRST("Congrats %s, you got 1st place!"),
  SECOND("Way to go %s, you got 2nd place!"),
  THIRD("Not bad %s, you got 3rd place!");

  private final String raceResultFormat;  
  Position(String raceResultFormat) {
    this.raceResultFormat = raceResultFormat;
  }

  public String raceResultMessageFor(String racer) {
    return String.format(raceResultFormat, racer);
  }
}

Thank you Jason Runkle for your reply and elaboration on this topic :slight_smile:
Much appreciated.

1 Like