Skip navigation links

Package proguard.classfile.visitor

This package contains interfaces and classes for processing class files from the proguard.classfile package using the visitor pattern.

See: Description

Package proguard.classfile.visitor Description

This package contains interfaces and classes for processing class files from the proguard.classfile package using the visitor pattern. Cfr., for instance, "Design Patterns, Elements of Reusable OO Software", by Gamma, Helm, Johnson, and Vlissider.

Why the visitor pattern? Class files frequently contain lists of elements of various mixed types: class items, constant pool entries, attributes,... These lists and types are largely fixed; they won't change much in future releases of the Java class file specifications. On the other hand, the kinds of operations that we may wish to perform on the class files may change and expand. We want to separate the objects and the operations performed upon them. This is a good place to use the visitor pattern.

Visitor interfaces avoid having to do series of instanceof tests on the elements of a list, followed by type casts and the proper operations. Every list element is a processable. When its accept method is called by a visitor, it calls its corresponding visitX method in the visitor, passing itself as an argument. This technique is called double-dispatch.

As already mentioned, the main advantage is avoiding lots of instanceof tests and type casts. Also, implementing a visitor interface ensures you're handling all possible processable types. Each type has its own method, which you simply have to implement.

A disadvantage is that the visitor methods always get the same names, specified by the visitor interface. These names aren't descriptive at all, making code harder to read. It's the visitor classes that describe the operations now.

Also, the visitor methods always have the same parameters and return values, as specified by the visitor interfaces. Passing additional parameters is done by means of extra fields in the visitor, which is somewhat of a kludge.

Because objects (the processables) and the operations performed upon them (the visitors) are now separated, it becomes harder to associate some state with the objects. For convenience, we always provide an extra visitor info field in processables, in which visitors can put any temporary information they want.

Skip navigation links