Search code examples
javaloopsdesign-patternsswitch-statementstrategy-pattern

How to avoid a loop-switch anti pattern


I am writting a regex parser for which, a loop-switch anti-pattern appears to be the only approach. Please ignore actual rules of parsing, as this parsing-logic is just custom made for an internal application, and deviant from common use.

 public static boolean match(String regex, String str) {
        int i = 0;
        int j = 0;

        while ((i < regex.length() && j < str.length())) {

            switch(regex.charAt(i)) {

            case '.' : i++; j++; break;

            case '*' : // do something ; break

            default  : if (regex.charAt(i) != str.charAt(j)) { return false; }  else {i++; j++};
            }
        }     
   }

How can the loop-switch be prevented in such a case ? Is there any design pattern meant for such a purpose ?


Solution

  • This is not the Loop-Switch Anti-Pattern!

    The anti-pattern occurs when a loop and switch is used to sequence some actions which could just be sequenced as statements in the program (in effect letting the processor's loop-switch known as the fetch-execute cycle handle it):

    for (step = 0; step < 3; step++) {
      switch (step) {
      case 0:
        do_the_first_thing();
        break;
      case 1:
        do_the_second_thing();
        break;
      case 2:
        do_the_third_thing();
        break;
      }
    }
    

    Instead of:

    do_the_first_thing();
    do_the_second_thing();
    do_the_third_thing();
    

    This isn't going on in your code. Your code is processing a regular expression, and so the cases can execute in whatever order is implied by the contents of the expression.

    In the above anti-pattern, de facto sequenced steps are hidden behind logic which appears to be prepared to deal with any order of execution; but in fact it doesn't process any data, only the loop dummy variable, which predictably steps from 0 to 2.