Loop-switch sequence
Encyclopedia
A loop-switch sequence is a programming antipattern where a clear set of steps is implemented as a switch-within-a-loop. The loop-switch sequence is a specific derivative of spaghetti code
Spaghetti code
Spaghetti code is a pejorative term for source code that has a complex and tangled control structure, especially one using many GOTOs, exceptions, threads, or other "unstructured" branching constructs. It is named such because program flow tends to look like a bowl of spaghetti, i.e. twisted and...

.

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-driven programming
In computer programming, event-driven programming or event-based programming is a programming paradigm in which the flow of the program is determined by events—i.e., sensor outputs or user actions or messages from other programs or threads.Event-driven programming can also be defined as an...

, event loop
Event loop
In computer science, the event loop, message dispatcher, message loop, message pump, or run loop is a programming construct that waits for and dispatches events or messages in a program...

 and event-driven finite state machine
Event-driven finite state machine
In computation, a finite-state machine is event driven if the transition from one state to another is triggered by an event or a message...

).

Note that this is not a performance antipattern, though it may lead to an inconsequential performance penalty due to the lack of an unrolled loop
Loop unwinding
Loop unwinding, also known as loop unrolling, is a loop transformation technique that attempts to optimize a program's execution speed at the expense of its binary size...

. Rather, this is a clarity antipattern, as in any non-trivial example, it is much more difficult to decipher the intent and actual function of the code than the more straightforward refactored solution.

Example

Here is an example of the antipattern:


// parse a key, a value, then three parameters
String key = null;
String value = null;
List params = new LinkedList;

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


And here is the refactored solution:


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

// parse 3 parameters
List params = new LinkedList;
for (int i = 0; i < 3; i++) {
params.add(stream.parse);
}
The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK