I still read too many switches

Yes, I still read too much code with switches inside. I hate it. There’s still also a “nice” page on the official website of Sun on how to write really nasty code, it’s here. I don’t wanna infect this blog, so I’m not pasting that example of code here. I paste only a quote, it says:

Deciding whether to use if-then-else statements or a switch statement is sometimes a judgment call.

Yes, indeed. And the judgment call is: “should I write a long list of if then else or maybe think on some kind of polymorphism?” The switch is not an option. Switch smells of poor design, smells of “you dude, writing that code, you don’t know what object oriented is!”. It’s not well testable, it’s ugly.

The web is plenty of examples on how to refactor from a switch to a decent design, just searching right now, I’ve found a good one here.

There’s another one here, with strategies for getting rid of it.

So why are you writing still switches? Let me know, we can talk about this and maybe I can help you to quit.

Switch off the switches. That’s the tip. :-)

Hey, this does not allow you to write a long chain of if then else blocks! Think on polymorphism every time you write an if, ask to your pair what he thinks, maybe you can move that responsibility somewhere else, one if is still fine but when you start to have an else… Mhmmm….

I really hope that someone is reading and I’ll read less switch stuff…

This entry was posted in Uncategorized and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

3 Comments

  1. Posted October 1, 2007 at 9:37 am | Permalink

    Hi, just a heads up – the second “here” link points to editing some post on this blog – redirecting to the login screen. Please fix :)

    Oh, and feel free to remove this comment afterwards – there isn’t much sense in it when the link is fix’ed.

    /by way of TW rss :)

  2. felix
    Posted October 1, 2007 at 1:05 pm | Permalink

    I can only agree. Switch just like if-else-ifs is a major cause to cancer of the developer’s eye. I am not sure whether you should spend too much time explaining all this. If people can’t see how this crap is bad, the most effective hazard mitigation is to shoot them on the spot.

  3. Posted October 1, 2007 at 1:37 pm | Permalink

    Thanks, I’ve just fixed the link ;-)

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>