switch versus if ... else if ... else

exercise No. 235

Q:

Consider a method computeItemCount() of following signature:

static int advanceItemCount() {...}

This method will be called by two different implementations of another method getScore():

Implementation by switch Implementation by if ... else if ... els
public static int getScore() {

  switch (advanceItemCount()){
    case 1: return 20;
    case 3: return 50;
    default: return 0;
  }
}
public static int getScore() {

  if (1 == advanceItemCount()) {
    return 20;
  } else if (3 == advanceItemCount()) {
    return 50;
  } else {
    return 0;
  }
}

An experienced programmer claims these two implementations possibly return different results when executing getScore(). Is she right? Explain your answer.

Tip

How often is advanceItemCount() being called? Consider possible side effects and provide an example.

A:

The difference between both implementations is about calling advanceItemCount() just once in the switch, but possibly two times in the if implementation variant. Consider:

public class X {
   private static int itemCount = 2;

    static int advanceItemCount() {return itemCount++;}
  ...
   public static int getScore() {/* either »switch« or »if« implementation */}
}

On a fresh start the switch implementation calling advanceItemCount() for the first time receives the initial itemCount value of 2. It will thus return its default value 0.

On contrary the if implementation will call advanceItemCount() two times:

  1. The first if (1 == advanceItemCount()) fails since 1 != 2. This results in incrementing itemCount by 1 to its new value of 3.

  2. Now the else if (3 == advanceItemCount()) clause succeeds returning 50.

For aligning both implementations we require a small modification on the if implementation:

public static int getScore() {

   final int count = advanceItemCount(); // Called only once

   if (1 == count) {
      return 20;
   } else if (3 == count) {
      return 50;
   } else {
      return 0;
   }
}