Object oriented design patterns for parsing text files?

As part of the software package I'm working on, I need to implement a parser for text files specific to the application. I already pointed out the grammar for these files on paper, but it's hard for me to translate it into easily readable / updatable code (right now it goes through every 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?

+6
source share
3 answers

Any easy way to break a massive switch into an OO design would 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 is your break of each switch statement in a method on this token object to determine if the next bit of the string is this type.

Earlier:

 class TokenParse { public void parseTokens(string data) { for each step in data { switch (step) { case x: ... case y: ... ... } } ... } } 
+5
source

One suggestion is to create a properties file in which you define the rules. Download it at runtime and use if else loop (since switch statements also do the same inside). Thus, if you want to change some parsing rules, you need to change the .property file, not the code. :)

+1
source

You need to learn how to express context-free grammars. You should think about GoF translator and parser / generators like Bison, ANTRL, lex / yacc etc.

0
source

Source: https://habr.com/ru/post/906710/


All Articles