Jump to content

Loop-switch sequence

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Aaron Rotenberg (talk | contribs) at 02:49, 18 March 2009 (General cleanup). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

A loop-switch sequence (also known as the for-case paradigm[1]) is a a programming antipattern where a clear set of steps is implemented as a byzantine switch-within-a-loop. The loop-switch sequence is a specific derivative of spaghetti code.

It is not necessarily an antipattern to use a switch statement within a loop—it is only considered incorrect when used to model a known sequence of steps. The most common example of the correct use of a switch within a loop is an event handler. In event handler loops, the sequence of events is not known at compile-time, so the repeated switch is both necessary and correct (see event-driven programming, event loop and event-driven finite state machine).

It is reasonable to check for the possible performance loss that having a conditional inside a loop could bring. Modern compilers are capable in some cases to transform the loop with conditional(s) into a construct with better performance (see loop unswitching); therefore, it may not always be worthwhile to eliminate these constructs for performance reasons alone, although it may benefit readability to do so.

Example

Here is an example of the antipattern:

// parse a key, a value, then three parameters 
String key;
String value;
List<String> args;

for (int i = 0; i < 5; i++) {
    switch(i) {
        case 0:
            key = stream.parse();
            break;
        case 1:
            value = stream.parse();
            break;
        default:
            args.add(stream.parse());
    }
}

And here is the refactored solution:

// parse a key and value
String key = stream.parse();
String value = stream.parse();

// parse 3 parameters
List<String> args;
for (int i = 0; i < 3; i++) {
    args.add(stream.parse());
}

References