Saturday, February 15, 2014

Called out on the Switch Statement

I was going over TDD with a developer and made a statement that I avoid using switch statements. (I may have used stronger language like "never use", can't remember.)  Then a few days later, I was pair programming with the same developer and I used a switch statement.  The developer, frustrated and confused, called me out on it.  
We were working on parsing XML sax style using xmlreader and writer.  I was also copy and pasting code from the sample as a first pass to quickly get my tests to pass.  If I needed to change... that is what refactoring is for.

While I was chopping wood for the fireplace, I was reflecting on this issue and I came up with the following.  On more than one occasion, I have had to refactor switch statements to either if else statements or, in some cases, a full blown rules engine.

I have nothing against the switch statement, other than it does not leave me much room for refactoring.  The "if" statement is reduced to a boolean in both the switch and if-else.  But in the switch statement one operator immutable throughout the evaluation set.  In contrast the "if-else" allows both sides of the equation to change at each decision point.

The XML example, using switch was fine.  The problem domain is fixed and backed by well established enumerations against a very mature standard.  When I am working out something new on my own, where both sides could change, I stick with the if statement or something else that is more flexible.