3

Recently, I had to implement an Abstract Query Tree for a research project. The base object is an ASTNode, but the actual tree nodes were derived classes: expression nodes, comparison nodes, operand nodes, etc. Each type of node has its own members, such as operand node(s), lists of arguments, and so forth.

The parsing functions that recursively generate this tree need to return ASTNode types, since they just return a pointer regardless of what type of node sits at the root of the generated tree.

This means that the functions that parse the tree need to query, for each node in the tree, what type it is, before operating on it. This can be done with dynamic casts or typeid, but SO and the Google style guidelines would get angry over my violation of the Liskov substitution principle and all the run-type type checks in general.

I can't put the functions that operate on the nodes in the node sub-classes themselves, since the trees can be used in several different ways in different parts of the application. Is there a better way to structure my trees?

mgiuffrida
  • 3,299
  • 1
  • 26
  • 27

2 Answers2

2

This looks like a good fit for the visitor pattern.

How to write the Visitor Pattern for Abstract Syntax Tree in Python?

http://en.wikipedia.org/wiki/Visitor_pattern

Community
  • 1
  • 1
fjardon
  • 7,921
  • 22
  • 31
1

Maybe composite pattern will be useful too. Also have a look at this article:

http://blog.jooq.org/2012/04/10/the-visitor-pattern-re-visited/

Ivan
  • 2,262
  • 1
  • 18
  • 16