1

I'm creating a pull parser and it relies heavily on reading characters in a sequential way. The state of the parser changes as characters are read, so we can say there is a "context" that designates how next characters are interpreted.

The problem is that I usually find that there are some methods that should be queries, but they also modify the state.

For example, this method:

private void string ReadIdentifier() 
{
    string identifier = ReadUntilTheseCharsAreFound("=", ";");
    if (this.lastChar != "=")
    {
        this.state = States.ReadingProperty;
    } 
    else 
    {
        this.state = States.ReadingValue;
    }

    return identifier;
}

As you can see, not only does this retrieve the identifier, but it also changes the state. If the last character was a "=", the state is one, and if it was ";" the state is another.

This doesn't conform to the CQS principle and I don't like it very much :(

But given that it's a parser, maybe it's the best way to do it. So my question is: can you think of a better way to do this without breaking CQS?

Thanks!

Dave Schweisguth
  • 36,475
  • 10
  • 98
  • 121
SuperJMN
  • 13,110
  • 16
  • 86
  • 185
  • 2
    Impossible to say from a single method, that is arguably an operation (Command), not a query. As a side note, you may want to have a look at monadic parser combinators. A basic idea for operations there is generally that you pass in a parser instance, apply a pure function and return a new parser instance that contains the new "state", where each function consumes a portion of the input. (see e.g. http://blogs.msdn.com/b/lukeh/archive/2007/08/19/monadic-parser-combinators-using-c-3-0.aspx, https://github.com/sprache/Sprache, https://github.com/linerlock/parseq, etc). – Alex Apr 07 '15 at 20:20
  • Just wow! Mind-blowing solution! – SuperJMN Apr 07 '15 at 20:32
  • Do you think the monadic parser combinators solutions fits well for a pull parser? I'm building a XAML reader. I'm too new to parsers, sorry. – SuperJMN Apr 07 '15 at 22:19
  • 1
    Yes I think it would. Although I would imagine that XAML parsing is a solved problem (see system.xaml.xamlservices). For something similar (but far simpler) using a monadic parser you could have a look at this example: https://github.com/sprache/Sprache/tree/master/src/XmlExample – Alex Apr 07 '15 at 23:16
  • Unfortunately, XAML Services are not cross-platform. That is what my parser is covering :) I would like to contact you, if it's possible. If you are "reachable", please, find my in Twitter (@SuperJMN) – SuperJMN Apr 07 '15 at 23:21

0 Answers0