17

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?

2

2 Answers 2

23

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.

-1

To put it very simply, you're nesting two different flow control methods, which makes the code harder to understand.

If you see a for loop, you generally assume that loop conditions will control the logic within the loop. But if you then nest a whole case statement inside, with all of its own logic, that goes out the window.

3
  • 3
    There's nothing inherently wrong with nesting two control flow structures. Sometimes you need to. But in this case it's useless. May 10, 2017 at 18:18
  • "which makes the code harder to understand." Boy, is that ever the understatement of the day/month/year. May 14, 2017 at 0:15
  • 1
    This is not why the for-case antipattern is stupid.
    – user253751
    Sep 3, 2020 at 10:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.