Jump to content

Loop-switch sequence

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Dcoetzee (talk | contribs) at 05:34, 2 October 2008 (Remove link - The word byzantine here has nothing at all to do with byzantine failure - it's just being used as a word). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

A loop-switch sequence is a specific derivative of the spaghetti code programming antipattern where a clear set of steps is implemented as a byzantine switch-within-a-loop. Also known as "The FOR-CASE paradigm" [1].

Note: it is not necessarily an antipattern to use a switch statement within a loop. It is only 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). Also regarding the alarm that could trigger the possible performance loss that a conditional inside a loop could bring. Today modern compilers are capable in some cases to transform the loop with conditional(s) into a construct with better performance. Therefore not constituting an anti-pattern in some cases and not worth to look at when maintaining code. (see Loop unswitching)

Example of antipattern (pseudocode)

  // 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() );
    }
  }

Refactored solution (pseudocode)

  // 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() );
  }