Monster Subroutine

A subroutine (function, etc.) which from a lack of refactoring has grown to enormous size - you know, the 30 page switch statements, the 1500 line while loops.

A common scenario and possible AntiPattern (I don't have a good name for it) arises from the addition of options that are not factored out, giving rise to code like:

   while(processing()) {
      if (model_1) || (model_2 && (config_flags & isFooEnabled)) {
         do_something();
         ... more doing ...
         }
      ... some other code ...
      if (model_1) || (model_2 && (config_flags & isFooEnabled)) {
         do_something_2();
         ... even more doing ...
         }
      ... a thousand lines like this
      } // of the while loop

This gives the code a hypnotic quality. Nest these constructs and it can take days to find the execution path for a given configuration of the system. -- RobertField

Yeah, I personally take the time to kill and eat anybody I catch doing stuff like that. I figure that'll


Exactly once in my 20+ year career have I written a monster subroutine that, in hindsight, I would do again the same way (under the same constraints). That particular monster routine held a per-opcode switch on an assembler for the NS16032. And it was big. 2500 lines of code if I recall correctly. And the monster switch wasn't a problem, either to get the assembler working, or to get it debugged. And for two years thereafter (until the company folded), no maintenance was necessary in that monster subroutine in the assembler.

We did consider options other than one big switch, but profiling a couple of prototypes showed that the big switch was the fastest by a significant margin. And we really did care about speed, since all of the code in development was passing through this assembler, sometimes many, many times a day, on 1985ish hardware. --DaveSmith

You better consider dividing that MonsterSubroutine using the TemplatePattern. I did the same once for handling keyboard keystrokes. Interestingly enough, most UI elements would handle their own processing using one big switch statement. The problem was that the same code was written in several UI elements and for some of them the switch was big. The solution was to add an intermediate class (in the class hierarchy) which would handle in one big switch statement all possible keystrokes. Ugly, isn't it? Well, no so much because any keystroke would invoke just one method named after the key that did nothing, so all that complexity became irrelevant. Any UI element would simply redefine the appropiate method. It became event driven programming and it was a joy to use it. -- GuillermoSchwarz


See GrandCentralStation


Contributors: RobertField, MartySchrader


EditText of this page (last edited April 28, 2006) or FindPage with title or text search