Anti-Patterns – What Is the For-Case Antipattern?

anti-patterns

Today's TDWTF article starts with a confession from the author:

I didn’t know what the For-Case anti-pattern was until relatively recently, when there were a spate of articles condemning it as an anti-pattern. I’m sure I’ve probably used it, at some point, but I never knew it by name. It’s thought of as a textbook antipattern that generally implies a misunderstanding of for loop, case statements, the problem being solved, or some combination of all three.

He then proceeds as if the reader, naturally, knows what the For-Case anti-pattern is without any further explanation being needed.

But I don't! I haven't seen the "spate of articles" that Remy talks about, and the only significant reference that I can find on Google (besides Remy's article) is a blog post by Raymond Chen about the for-if antipattern, which is apparently related. He doesn't define the "for-case anti-pattern" either, though.

What is this "For-Case anti-pattern" that these guys are talking about, and what makes it an anti-pattern?

Best Answer

The "pattern" was introduced in an earlier Daily WTF article. The basic idea is that you have a for loop with a case inside of it that selects based on the for loop index variable.

Assuming the index variable can't be changed inside the loop, (which is not always true, depending on which language you're using,) a bit of analysis demonstrates that the execution is exactly the same as if you removed the for and the case entirely and all the case blocks were simply executed sequentially.

Related Topic