Visitor pattern revisited in D

Michal Minich michal.minich at gmail.com
Mon Aug 27 09:47:38 PDT 2012


On Monday, 27 August 2012 at 16:28:24 UTC, deadalnix wrote:
> Le 27/08/2012 18:02, Michal Minich a écrit :
>> On Monday, 27 August 2012 at 15:00:11 UTC, deadalnix wrote:
>>> /!\ Shameless autopromotion incoming /!\
>>>
>>> I have recently put some effort into exploring alternatives 
>>> to visitor
>>> pattern and see what can be done in D. I ended up with a 
>>> solution
>>> which is a real improvement compared to plein old visitor 
>>> pattern and
>>> wanted to share this here.
>>>
>>> I think this is short enough to be a good example to show 
>>> what can be
>>> done with D capabilities.
>>>
>>> http://www.deadalnix.me/2012/08/25/visitor-pattern-revisited-in-d/
>>
>> This is nice use of d magic. If the implementation could 
>> recompute the
>> functions pointers during compilation, this seems as nice 
>> generally
>> function. This makes me thing of computed goto (to functions)
>>
>> One possibility to achieve this result for visitor is to use 
>> mixin.
>>
>> I would mixin implementation of accept method into very node 
>> super
>> class. This is to avoid code duplication.
>>
>> Secondly, I would mixin implementation of opDispatch that 
>> simply does
>> nothing/throws to every implementation of visitor. This is to 
>> avoid
>> empty implementations of visit methods which are not needed for
>> particular visitor.
>
> This can only work if you know all node type by advance. Which 
> is one limitation of the visitor pattern I intended to solve.

The opDispatch would only handle non existing methods in visitor. 
It could be defined to throw, or each  visitor could define one 
doing generic thing for that visitor (ie return null), or visitor 
could not use opDispatch at all.

Generally I think default imlementations of interface methods - 
such as to throw/do nothing/return null should not be used. Then 
I think is better to split the interface/hierarchy of clases. 
This may not be allways better solution. Large hierarchy of 
clases can be hiding some middle clases, wich could lead to 
beterr desing, if lucky. But here it depend on specifics if its 
better to introduce hierarchy, or handle  some specifics here and 
there.


More information about the Digitalmars-d-announce mailing list