←back to thread

1087 points smartmic | 4 comments | | HN request time: 0.908s | source
Show context
12_throw_away ◴[] No.44303909[source]
This has by far the best discussion of the visitor pattern I've yet to come across.
replies(3): >>44304154 #>>44304309 #>>44304662 #
dgb23 ◴[] No.44304309[source]
I don't work in typical OO codebases, so I wasn't aware of what the visitor pattern even is. But there's an _excellent_ book about building an interpreter (and vm) "crafting interpreters". It has a section where it uses the visitor pattern.

https://craftinginterpreters.com/representing-code.html#the-...

I remember reading through it and not understanding why it had to be this complicated and then just used a tagged union instead.

Maybe I'm too stupid for OO. But I think that's kind of the point of the grug article as well. Why burden ourselves with indirection and complexity when there's a more straight forward way?

replies(6): >>44304428 #>>44304648 #>>44304698 #>>44304986 #>>44306960 #>>44316589 #
1. recursivedoubts ◴[] No.44304648[source]
I love crafting interpreters and mention it on grugbrain:

https://grugbrain.dev/#grug-on-parsing

but the visitor pattern is nearly always a bad idea IMO: you should just encode the operation in the tree if you control it or create a recursive function that manually dispatches on the argument type if you don't

replies(1): >>44316626 #
2. zelphirkalt ◴[] No.44316626[source]
An implementor of a data structure might take precautions for users of the data structure to perform such visiting operations by passing in a visitor-like thing.
replies(1): >>44319782 #
3. recursivedoubts ◴[] No.44319782[source]
I just don't think it's a significantly better way of dealing w/the problem than a recursive function that dispatches on the arg type (or whatever) using an if statement or pattern matching or whatever.

The additional complexity doesn't add significant value IMO. I admit that's a subjective claim.

replies(1): >>44320748 #
4. zelphirkalt ◴[] No.44320748{3}[source]
I mean, at some point you can also make that recursive function take an argument, that decides what to do depending on the type of the item, to make that recursive function reusable, if one has multiple use-cases ... but that's basically the same as the visitor pattern. There really isn't much to it, other than programming language limitations, that necessitate a special implementation, "making it a thing". Like when Java didn't have lambdas and one needed to make visitors objects, ergo had to write a class for them.