Visitor Pattern

I was trying to implement the visitor pattern in checkSemantics. I realized that in order to implement that pattern, we should be able to reach the properties of the class that we are going to use. In this sense we should either have the properties public or have the getter classes.

Lets say we are going to implement checkSemantics() for the Functions, FunctionDeclarations and GlobalVariables. We should be able to reach the parameters and/or the block in visitor implementation.

In that sense, I wanted to prefer implementing the functions locally in the particular classes itself since I feel more safe or maybe I just got lazy for it. I also assume that we don’t have to use visitor pattern to do the project - by implementing every function in the particular classes.

I just wanted to be sure about whether I understand properly and see whether you have any comments on that.

Yes, for the visitor pattern, you need a way to transport important state information to the visitor to work on.

Sometimes this includes part of the internal state.
One option to solve this problem is making the state public or with controlled access using methods (only getter for read-only or wrappers for partial access).

Another way would be to modify the visitor pattern to allow for wrapped/copied internal state access.

It is important to note that the visitor pattern

  • Is not always applicable / the best choice
  • Is not a hard rule to follow but rather a guideline.

You can solve the project completely without the visitor pattern.
But you can also use ideas or the whole pattern if you like and think it makes your workflow simpler.
In the end, it is up to you, how you want to design your code.

1 Like

As Marcel mentioned, you’re not required to use a visitor. In fact, my implementation also does not.

It’s completely fine here, especially since you know from the start which kinds of expressions (and which functionality) you need. The visitor pattern is particularly useful if you later want to expand the number of variants, or the kind of functionality your objects should implement. Here, neither is the case.

Note that your visitor would also need to modify the classes it’s visiting, in order to add the annotations needed to later compile / verify the code.

1 Like