Switch Follow-up

I think it is necessary to explain why I said I considered switch to be code smell.

My definition of “code smell”:

May indicate bad design!

Notice the “may”? I keep forgetting that one myself. Not every appearance of a code smell is evidence of bad design per se. One should simply consider getting rid of the smell. Calling something a code smell should just make the programmer step carefully around certain constructs.

Now to the question is switch a code smell?

A switch is the equivalent of a big bunch of if-else statements complete with funky opportunities for errors (missing breaks or default). I personally associate “big bunches of if-else” with hard to read, error-prone code that should better be designed differently. Oh wait, a code smell (see definition). Of course sometimes you just cannot get rid of it. And a switch sometimes is already an improvement to the “if-else” mess. (I have heard someone talking of a class with 50 (!!!) consecutive if statements. I will always question that kind of design until someone proves that it is the best possible solution!)

Secondly most of my uses of switch in the past were very obviously nothing better than “if-instanceof-else-instanceof” hidden behind a mask. This can (and should be IMHO) refactored with “replace switch by polymorphism”.

Thirdly in this particular case I still have my boss’ question ringing in the ear: “Can’t you get rid of that switch?”

On the other hand a well-implemented switch shows very clearly what’s happening and is easy to read. Most people know switch statements as opposed to constant specific methods or anonymous classes and the errors that can occur around switch statements are well-known and easy to avoid.

There are probably more and better arguments pro and contra this particular issue. After listing all these, I finally understood that my problem wasn’t whether a switch is code smell. I was talking about a particular piece of code and my personal opinion plays a large part in defining the code smell attribute. I had seen something I considered code smell and tried to get rid of it because it was code smell without thinking beyond.

I got rid of the switch as described here took one look at it, slept a few hours and the next day I had lots of fun with cvs 🙁 getting back to the old version. That particular switch remains in place. I had to try the alternative though, to be able to defend a construct I don’ t like.

Fazit: I learned to not forget the “may” in the “may indicate bad design” and that what everyone considers “evil design” may sometimes be a matter of taste, application or programming language.

PS: “May” is such a cool word to open yourself a couple of loopholes to escape your own opinion by!

One Reply to “Switch Follow-up”

  1. Pingback: /dev/blog

Comments are closed.