Jump to content

Loop-switch sequence

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Alaibot (talk | contribs) at 06:59, 6 December 2006 (Robot tagging as uncategorised). 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 which describes the obfuscating of a clear process of steps with a byzantine switch-within-a-loop idiom. However, it is not necessarily an anti-pattern to use a switch within a loop to build a coroutine that handles events using a finite state machine.

Example of antipattern (pseudocode)

  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)

If a delay (or the execution of another fiber) is not required between calls, the above may be refactored as follows:

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