3

inside my java programm I need to have a control-structure which should give 3 different outcomes to 3 different inputs.

Input 1: Text 1

Input 2: Text 2

Input 3: Text 3

My Question here is: Best-Practice wise and efficiency wise, which control structure should be used? My First thought has been a switch case, but why would I choose that over IF-Structures or nested ? operators??

blacksmth
  • 55
  • 1
  • 1
  • 7
  • Possible duplicate: http://stackoverflow.com/questions/3387758/java-case-statment-or-if-statement-efficiency-perspective – acostache Dec 07 '12 at 09:07
  • what do you mean with duplicate? in your linked question, there is a general question. mine is specific for 3 possibilites. – blacksmth Dec 07 '12 at 09:11
  • First a wrote related, then i changed to possible duplicate - so it's just a general related one - my bad – acostache Dec 07 '12 at 09:13

3 Answers3

3

you should strive for good readability first, then for efficiency if required. If there are many options, use switch if small, use if/else

vishal_aim
  • 7,636
  • 1
  • 20
  • 23
3

I think you'll find it generally agreed that the switch statement is mildly preferred in this situation, purely on the basis of readability. It scales a lot better if additional cases are added and even with three options, it's still a bit more readable, particularly with the cases being simply three variations of one input. Performance differences are negligible but there are surely discussions out there if you really want to get into that specific aspect.

I'd suggest avoiding the ternary operator (i.e., inline if/'?') for any more than two cases for similar reasons of readability. Personally, I don't parse it as well and I avoid it unless all expressions involved are very brief.

Mostly off-topic, but interestingly, switching on Strings wasn't added to Java til Java 7.

David Duncan
  • 1,225
  • 8
  • 14
1

Maybe a nested ternary operator? Just kidding. I think efficiency here is going to be almost identical whatever structure is used. I would go for the if/else because I think is more readable than a swtich (an less error prone -don't forget the breaks-) but it's just an opinion.

Averroes
  • 4,168
  • 6
  • 50
  • 63