Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object oriented design patterns for parsing text files?

As part of a software package I'm working on, I need to implement a parser for application specific text files. I've already specified the grammar for these file on paper, but am having a hard time translating it into easily readable/updatable code (right now just it passes each line through a huge number of switch statements).

So, are there any good design patterns for implementing a parser in a Java style OO environment?

like image 246
zergylord Avatar asked Jan 23 '12 23:01

zergylord


1 Answers

Any easy way to break a massive switch into an OO design would be to have

pseudo code

class XTokenType {
     public bool isToken(string data);
}

class TokenParse {
     public void parseTokens(string data) {
          for each step in data {
               for each tokenType in tokenTypess {
                    if (tokenType.isToken(step)) {
                         parsedTokens[len] = new tokenType(step);
                    }
                    ...
               }
          }
          ...
     }
}

Here your breaking each switch statement into a method on that token object to detect whether the next bit of the string is of that token type.

Previously:

class TokenParse {
     public void parseTokens(string data) {
          for each step in data {
               switch (step) {
                    case x: 
                         ...
                    case y:
                         ...
                    ...
               }
          }
          ...
     }
}
like image 178
Raynos Avatar answered Oct 21 '22 05:10

Raynos