Case Study of Writing the Extensible Visitor Pattern
From APIDesign
Have You Ever Wondered...?
Do you wonder whether knowledge of proper design patterns makes you good API designer? Yes and no. Of course knowing regular design patterns simplifies communication, understanding, etc. However there are hidden catches. Not every design pattern belongs among APIDesignPatterns - it may not be ready for evolution. For example the well known Visitor pattern is really not evolvable easily as analysed by Chapter 18.
Tripple Dispatch
The Chapter 18 discusses various approaches to implement visitor in an evolvable API. The learning path itself is important, but to stress the important point, here is the code for the final solution of the expression problem:
does not exists: visitor.clientprovider.v1
The solution is using Java interfaces to represent expression elements and yet it is fully evolvable (one can always define new expression element interface). Visitor is not just a single class, but one Java interface and one Java final class. Visitors written using this style are easily extensible. For example when adding support for Minus operation in version 2.0 one just adds:
does not exists: visitor.clientprovider.v2
This is the most flexible solution. It uses a form of tripple dispatch - e.g. the final visit method called on the (implementation of the visitor interface) is determined by the expression type, version of the expression language and implementation of the visitor interface:
does not exists: visitor.clientprovider.dispatch.v3.l2
This solution to the expression problem is another realization of the general principle to separate ClientAPI from ProviderAPI. Client part of the visitor is enriched by new and new dispatch methods with every version. The interface part of visitor is immutable, a fixed point, which stays the same for those who implement it. Each version defines its own unique interface (according to the list of expression types it supports). The internals of the API then bridge the dispatch methods to appropriate interface visit methods.
<comments/>