News for hackers. Stuff that matters.
Re:If-else vs switch – Which is better? by larryfreeman on Sunday August 02, 2009 @10:35PM (#738482)
Often times, there is a third choice: polymorphism using interfaces.

Consider an example from the article:

public static void testIfElse(int jumpLabel) {

if(1 == jumpLabel) {

    System.out.println("1");
} else if(2 == jumpLabel) {

    System.out.println("2");
} else if(3 == jumpLabel) {

    System.out.println("3");
} else if(4 == jumpLabel) {

    System.out.println("4");
}

// Removed for simplicity

else {

    System.out.println("default");
}

}

Why not implement this as follows:

public interface IfElse {

   public void testIfElse();
}

public class JumpLabelDefault implements IfElse {

   public void testIfElse() {

      System.out.println("Default"); 

   }
}

public class JumpLabel1 implements IfElse {

   public void testIfElse() {

      System.out.println("1");

   }
}

...

Then, to do the same test, you have this function:

public static void testIfElse(IfElse obj) {

   obj.testIfElse();
}

This is faster than either an if-else statement or a switch statement and you can easily add new cases by creating new objects without needing to change the previous code.

I'm not sure why this option is not included in the article.

Re:If-else vs switch – Which is better? by gaius on Monday August 03, 2009 @12:24AM (#738609)
And to think people say Java is verbose!
Re:If-else vs switch – Which is better? by ramchip on Monday August 03, 2009 @11:00AM (#739332)
Is this a joke?