switch-case construct – used in various programming languages, including PHP – is a curious beast. Most commonly used as a streamlined form of
if-elseif-else, it actually has more in common with the oldest of control statements, the
goto, since control jumps to the first match and carries on until you tell it to stop.
Firstly, am I the only person in the world who thinks that the
break should be indented to the same level as the
case, not the level of the commands between? If you are using it as a series of separate
elseif blocks, then surely the two form a matching pair, with the code block “enclosed” within them. Of course, you can generally
break early inside the code, just like you can
return early from a function, which is hard to make stand out – but that’s just an argument not to do it too often!
And, of course, the fact that another
case comes along does not mean that the code won’t carry on. Which brings me neatly to my next thought: is there any language that insists you declare when you’re falling through to the next case – and if not, why not? What if every time you put a
case, you had to end it with either a
break or a
continue? It seems to me it would prevent a lot of bugs caused by cases inadvertently falling through and running completely the wrong code. And if overloading an existing term like
continue is too confusing, lets just have a
fallthrough – anyone got a case against? [No pun intended; probably…]