57

I am looking for an alternative to the visitor pattern. Let me just focus on a couple of pertinent aspects of the pattern, while skipping over unimportant details. I'll use a Shape example (sorry!):

  1. You have a hierarchy of objects that implement the IShape interface
  2. You have a number of global operations that are to be performed on all objects in the hierarchy, e.g. Draw, WriteToXml etc...
  3. It is tempting to dive straight in and add a Draw() and WriteToXml() method to the IShape interface. This is not necessarily a good thing - whenever you wish to add a new operation that is to be performed on all shapes, each IShape-derived class must be changed
  4. Implementing a visitor for each operation i.e. a Draw visitor or a WirteToXml visitor encapsulates all the code for that operation in one class. Adding a new operation is then a matter of creating a new visitor class that performs the operation on all types of IShape
  5. When you need to add a new IShape-derived class, you essentially have the same problem as you did in 3 - all visitor classes must be changed to add a method to handle the new IShape-derived type

Most places where you read about the visitor pattern state that point 5 is pretty much the main criteria for the pattern to work and I totally agree. If the number of IShape-derived classes is fixed, then this can be a quite elegant approach.

So, the problem is when a new IShape-derived class is added - each visitor implementation needs to add a new method to handle that class. This is, at best, unpleasant and, at worst, not possible and shows that this pattern is not really designed to cope with such changes.

So, the question is has anybody come across alterative approaches to handling this situation?

5
  • Just an aside note, as it is unlikely that you can change your language: There are languages that directly support multiple dispatch generic functions.
    – Svante
    Jun 12, 2009 at 14:21
  • 9
    Great question. I just wanted to provide a counterpoint. Sometimes your issue with (5) can be a good thing. I use the visitor pattern when I have some functionality that must be updated when a new IShape subtype is defined. I have a IShapeVisitor interface that defines what methods are needed. As long as that interface is updated with the new subtype, my code doesn't build until the critical functionality is updated. For some situations, this can be very helpful.
    – oillio
    Apr 4, 2013 at 19:19
  • 1
    I agree with @oillio, but then you could also enforce it as an abstract method on IShape. What the Visitor pattern buys you in a pure OO language is locality of the function (vs. locality of class) and thereby a seperation of concerns. In any case, usign the visitor pattern should explicitly break at compile time when you want to force addition of new types to be reviewed carefully! Jul 18, 2015 at 10:37
  • 2
    "all visitor classes must be changed to add a method to handle the new IShape-derived type": I would not say that's a "problem". I would say this is a very nice security in your design. It guarantees that the newly added class is considered in every place where you do per-type specific operations (i.e.: in every place where we defined a visitor....if you don't consider the newly added type, compiler won't let you go...).
    – jpo38
    Feb 9, 2016 at 19:59
  • @jpo38 it's a concrete limitation if you need to allow 3rd-party code to declare its own subclasses that can be part of the hierarchy. The 3rd-party code would have no way to patch additional methods into the visitor interface.
    – Andy
    Oct 26, 2023 at 5:53

9 Answers 9

16

You might want to have a look at the Strategy pattern. This still gives you a separation of concerns while still being able to add new functionality without having to change each class in your hierarchy.

class AbstractShape
{
    IXmlWriter _xmlWriter = null;
    IShapeDrawer _shapeDrawer = null;

    public AbstractShape(IXmlWriter xmlWriter, 
                IShapeDrawer drawer)
    {
        _xmlWriter = xmlWriter;
        _shapeDrawer = drawer;
    }

    //...
    public void WriteToXml(IStream stream)
    {
        _xmlWriter.Write(this, stream);

    }

    public void Draw()
    {
        _drawer.Draw(this);
    }

    // any operation could easily be injected and executed 
    // on this object at run-time
    public void Execute(IGeneralStrategy generalOperation)
    {
        generalOperation.Execute(this);
    }
}

More information is in this related discussion:

Should an object write itself out to a file, or should another object act on it to perform I/O?

7
  • I've marked this as the answer to my question as I think this, or some minor variation on it, probably fits into what I want to do. For anyone whose interested, I've added an "answer" that describes some of my thoughts on the problem
    – Steg
    Jun 22, 2009 at 12:51
  • ok - changed my mind about the answer thing - I'll try to condense it into a comment (following)
    – Steg
    Jun 22, 2009 at 12:52
  • 4
    I think there is a fundamental conflict here - if you have a bunch of things and a bunch of actions that can be performed on these things then adding a new thing means that you must define the effect of all actions on it and vice versa - there is no escaping this. The visitor provides a very simple, elegant way of adding new actions at the expense of making it difficult to add new things. If this constraint must be relaxed, the you have to pay. I was hoping there might be solution that has the elegance and simplicity of the visitor, but as I suspected, I don't think one exists...cont'd...
    – Steg
    Jun 22, 2009 at 13:06
  • so, I think that this answer probably suits my current needs and I find it appealing because it is simpler than some of the other suggestions. Anyway, thanks to all for taking time to answer
    – Steg
    Jun 22, 2009 at 13:09
  • 1
    @jungle_mole Perhaps my solution is a bit similar to the one you have described here?
    – Vahid
    Nov 10, 2018 at 12:29
13

There is the "Visitor Pattern With Default", in which you do the visitor pattern as normal but then define an abstract class that implements your IShapeVisitor class by delegating everything to an abstract method with the signature visitDefault(IShape).

Then, when you define a visitor, extend this abstract class instead of implementing the interface directly. You can override the visit* methods you know about at that time, and provide for a sensible default. However, if there really isn't any way to figure out sensible default behavior ahead of time, you should just implement the interface directly.

When you add a new IShape subclass, then, you fix the abstract class to delegate to its visitDefault method, and every visitor that specified a default behavior gets that behavior for the new IShape.

A variation on this if your IShape classes fall naturally into a hierarchy is to make the abstract class delegate through several different methods; for example, an DefaultAnimalVisitor might do:

public abstract class DefaultAnimalVisitor implements IAnimalVisitor {
  // The concrete animal classes we have so far: Lion, Tiger, Bear, Snake
  public void visitLion(Lion l)   { visitFeline(l); }
  public void visitTiger(Tiger t) { visitFeline(t); }
  public void visitBear(Bear b)   { visitMammal(b); }
  public void visitSnake(Snake s) { visitDefault(s); }

  // Up the class hierarchy
  public void visitFeline(Feline f) { visitMammal(f); }
  public void visitMammal(Mammal m) { visitDefault(m); }

  public abstract void visitDefault(Animal a);
}

This lets you define visitors that specify their behavior at whatever level of specificity you wish.

Unfortunately, there is no way to avoid doing something to specify how visitors will behave with a new class - either you can set up a default ahead of time, or you can't. (See also the second panel of this cartoon )

6

I maintain a CAD/CAM software for metal cutting machine. So I have some experience with this issues.

When we first converted our software (it was first released in 1985!) to a object oriented designed I did just what you don't like. Objects and Interfaces had Draw, WriteToFile, etc. Discovering and reading about Design Patterns midway through the conversion helped a lot but there were still a lot of bad code smells.

Eventually I realized that none of these types of operations were really the concern of the object. But rather the various subsystems that needed to do the various operations. I handled this by using what is now called a Passive View Command object, and well defined Interface between the layers of software.

Our software is structured basically like this

  • The Forms implementing various Form Interface. These forms are a thing shell passing events to the UI Layer.
  • UI layer that receives Events and manipulate forms through the Form interface.
  • The UI Layer will execute commands that all implement the Command interface
  • The UI Object have interfaces of their own that the command can interact with.
  • The Commands get the information they need, process it, manipulates the model and then report back to the UI Objects which then does anything needed with the forms.
  • Finally the models which contains the various objects of our system. Like Shape Programs, Cutting Paths, Cutting Table, and Metal Sheets.

So Drawing is handled in the UI Layer. We have different software for different machines. So while all of our software share the same model and reuse many of the same commands. They handle things like drawing very different. For a example a cutting table is draw different for a router machine versus a machine using a plasma torch despite them both being esstentially a giant X-Y flat table. This because like cars the two machines are built differently enough so that there is a visual difference to the customer.

As for shapes what we do is as follows

We have shape programs that produce cutting paths through the entered parameters. The cutting path knows which shape program produced. However a cutting path isn't a shape. It just the information needed to draw on the screen and to cut the shape. One reason for this design is that cutting paths can be created without a shape program when they are imported from a external app.

This design allows us to separate the design of the cutting path from the design of the shape which are not always the same thing. In your case likely all you need to package is the information needed to draw the shape.

Each shape program has a number of views implementing a IShapeView Interface. Through the IShapeView interface the shape program can tell the generic shape form we have how to setup itself up to show the parameters of that shape. The generic shape form implements a IShapeForm interface and registers itself with the ShapeScreen Object. The ShapeScreen Object registers itself with our application object. The shape views use whatever shapescreen that registers itself with the application.

The reason for the multiple views that we have customers that like to enter shapes in different ways. Our customer base is split in half between those who like to enter shape parameters in a table form and those who like to enter with a graphical representation of the shape in front of them. We also need to access the parameters at times through a minimal dialog rather than our full shape entry screen. Hence the multiple views.

Commands that manipulate shapes fall in one of two catagories. Either they manipulate the cutting path or they manipulate the shape parameters. To manipulate the shape parameters generally we either throw them back into the shape entry screen or show the minimal dialog. Recalculate the shape, and display it in the same location.

For the cutting path we bundled up each operation in a separate command object. For example we have command objects

ResizePath RotatePath MovePath SplitPath and so on.

When we need to add new functionality we add another command object, find a menu, keyboard short or toolbar button slot in the right UI screen and setup the UI object to ececute that command.

For example

   CuttingTableScreen.KeyRoute.Add vbShift+vbKeyF1, New MirrorPath

or

   CuttingTableScreen.Toolbar("Edit Path").AddButton Application.Icons("MirrorPath"),"Mirror Path", New MirrorPath

In both instances the Command object MirrorPath is being associated with a desired UI element. In the execute method of MirrorPath is all the code needed to mirror the path in a particular axis. Likely the command will have it's own dialog or use one of the UI elements to ask the user which axis to mirror. None of this is making a visitor, or adding a method to the path.

You will find that a lot can be handled through bundling actions into commands. However I caution that is not a black or white situation. You will still find that certain things work better as methods on the original object. In may experience I found that perhaps 80% of what I used to do in methods were able to be moved into the command. The last 20% just plain work better on the object.

Now some may not like this because it seems to violate encapsulations. From maintaining our software as a object oriented system for the last decade I have to say the MOST important long term thing you can do is clearly document the interactions between the different layers of your software and between the different objects.

Bundling actions into Command objects helps with this goal way better than a slavish devotion to the ideals of encapsulation. Everything that is needs to be done to Mirror a Path is bundled in the Mirror Path Command Object.

1
  • The solution seems interesting, but i would appreciate if you could refer me to example code for such solution to better understand the concept.
    – Basil Musa
    Dec 4, 2017 at 13:13
4

Visitor design pattern is a workaround, not a solution to the problem. Short answer would be pattern matching.

1
  • 2
    Your answer could be improved by explaining why pattern matching is relevant, rather than just providing a link to an external website. Apr 7, 2021 at 13:00
2

Regardless of what path you take, the implementation of alternate functionality that is currently provided by the Visitor pattern will have to 'know' something about the concrete implementation of the interface that it is working on. So there is no getting around the fact that you are going to have to write addition 'visitor' functionality for each additional implementation. That said what you are looking for is a more flexible and structured approach to creating this functionality.

You need to separate out the visitor functionality from the interface of the shape.

What I would propose is a creationist approach via an abstract factory to create replacement implementations for visitor functionality.

public interface IShape {
  // .. common shape interfaces
}

//
// This is an interface of a factory product that performs 'work' on the shape.
//
public interface IShapeWorker {
     void process(IShape shape);
}

//
// This is the abstract factory that caters for all implementations of
// shape.
//
public interface IShapeWorkerFactory {
    IShapeWorker build(IShape shape);
    ...
}

//
// In order to assemble a correct worker we need to create
// and implementation of the factory that links the Class of
// shape to an IShapeWorker implementation.
// To do this we implement an abstract class that implements IShapeWorkerFactory
//
public AbsractWorkerFactory implements IShapeWorkerFactory {

    protected Hashtable map_ = null;

    protected AbstractWorkerFactory() {
          map_ = new Hashtable();
          CreateWorkerMappings();
    }

    protected void AddMapping(Class c, IShapeWorker worker) {
           map_.put(c, worker);
    }

    //
    // Implement this method to add IShape implementations to IShapeWorker
    // implementations.
    //
    protected abstract void CreateWorkerMappings();

    public IShapeWorker build(IShape shape) {
         return (IShapeWorker)map_.get(shape.getClass())
    }
}

//
// An implementation that draws circles on graphics
//
public GraphicsCircleWorker implements IShapeWorker {

     Graphics graphics_ = null;

     public GraphicsCircleWorker(Graphics g) {
        graphics_ = g;
     }

     public void process(IShape s) {
       Circle circle = (Circle)s;
       if( circle != null) {
          // do something with it.
          graphics_.doSomething();
       }
     }

}

//
// To replace the previous graphics visitor you create
// a GraphicsWorkderFactory that implements AbstractShapeFactory 
// Adding mappings for those implementations of IShape that you are interested in.
//
public class GraphicsWorkerFactory implements AbstractShapeFactory {

   Graphics graphics_ = null;
   public GraphicsWorkerFactory(Graphics g) {
      graphics_ = g;
   }

   protected void CreateWorkerMappings() {
      AddMapping(Circle.class, new GraphicCircleWorker(graphics_)); 
   }
}


//
// Now in your code you could do the following.
//
IShapeWorkerFactory factory = SelectAppropriateFactory();

//
// for each IShape in the heirarchy
//
for(IShape shape : shapeTreeFlattened) {
    IShapeWorker worker = factory.build(shape);
    if(worker != null)
       worker.process(shape);
}

It still means that you have to write concrete implementations to work on new versions of 'shape' but because it is completely separated from the interface of shape, you can retrofit this solution without breaking the original interface and software that interacts with it. It acts as a sort of scaffolding around the implementations of IShape.

1
  • in AbstractWorkerFactory you still have to do instanceof Dec 25, 2013 at 7:46
1

If you have n IShapes and m operations that behave differently for each shape, then you require n*m individual functions. Putting these all in the same class seems like a terrible idea to me, giving you some sort of God object. So they should be grouped either by IShape, by putting m functions, one for each operation, in the IShape interface, or grouped by operation (by using the visitor pattern), by putting n functions, one for each IShape in each operation/visitor class.

You either have to update multiple classes when you add a new IShape or when you add a new operation, there is no way around it.


If you are looking for each operation to implement a default IShape function, then that would solve your problem, as in Daniel Martin's answer: https://stackoverflow.com/a/986034/1969638, although I would probably use overloading:

interface IVisitor
{
    void visit(IShape shape);
    void visit(Rectangle shape);
    void visit(Circle shape);
}

interface IShape
{
    //...
    void accept(IVisitor visitor);
}
1
  • Hi, I think that there are solutions like object algebras and I am quite sure that are other solutions to the expression problem.
    – Thomas2033
    Jun 10, 2023 at 11:59
1

I have actually solved this problem using the following pattern. I do not know if it has a name or not!

public interface IShape
{
}

public interface ICircleShape : IShape
{
}

public interface ILineShape : IShape
{
}

public interface IShapeDrawer
{
    void Draw(IShape shape);

    /// <summary>
    /// Returns the type of the shape this drawer is able to draw!
    /// </summary>
    Type SourceType { get; }
}

public sealed class LineShapeDrawer : IShapeDrawer
{
    public Type SourceType => typeof(ILineShape);
    public void Draw(IShape drawing)
    {
        if (drawing is ILineShape)
        {
            // Code to draw the line
        }
    }
}

public sealed class CircleShapeDrawer : IShapeDrawer
{
    public Type SourceType => typeof(ICircleShape);
    public void Draw(IShape drawing)
    {
        if (drawing is ICircleShape)
        {
            // Code to draw the circle
        }
    }
}

public sealed class ShapeDrawingClient
{
    private readonly IDictionary<Type, IShapeDrawer> m_shapeDrawers =
        new Dictionary<Type, IShapeDrawer>();

    public void Add(IShapeDrawer shapeDrawer)
    {
        m_shapeDrawers[shapeDrawer.SourceType] = shapeDrawer;
    }

    public void Draw(IShape shape)
    {
        Type[] interfaces = shape.GetType().GetInterfaces();
        foreach (Type @interface in interfaces)
        {
            if (m_shapeDrawers.TryGetValue(@interface, out IShapeDrawer drawer))
              {
                drawer.Draw(drawing); 
                return;
              }

        }
    }
}

Usage:

        LineShapeDrawer lineShapeDrawer = new LineShapeDrawer();
        CircleShapeDrawer circleShapeDrawer = new CircleShapeDrawer();

        ShapeDrawingClient client = new ShapeDrawingClient ();
        client.Add(lineShapeDrawer);
        client.Add(circleShapeDrawer);

        foreach (IShape shape in shapes)
        {
            client.Draw(shape);
        }

Now if someone as the user of my library defines IRectangleShape and wants to draw it, they can simply define IRectangleShapeDrawer and add it to ShapeDrawingClient's list of drawers!

1
  • This isn't providing a distinct method for each class. It is only acting on interface types and is not considering differences between multiple classes implementing the same interface. In your example you could have a bunch of classes that all implement ICircleShape (Globe, BowlingBall, and Clock) and it will draw them all the same. If your code to draw the circle simply calls an implementation method on ICircleShape then you're right back at implementing all the code in the classes. Oct 26, 2023 at 0:46
1

If you're using Java: Yes, it's called instanceof. People are overly scared to use it. Compared to the visitor pattern, it's generally faster, more straightforward, and not plagued by point #5.

Update: "whenever you wish to add a new operation that is to be performed on all shapes, each IShape-derived class must be changed" - this is a shortcoming of some languages. Java stewards realized this and added support for interface method default implementations, so this is less of an issue:

interface IShape {
    default void someNewOperation() {
        // some code...
    }
}

A similar way of accomplishing this in TypeScript would be

interface IShape {
  someNewOperation?: () => void;
}

function defaultSomeNewOperation(shape: IShape) {
  // some code...
}

function performSomeNewOperation(shape: IShape) {
  if (shape.someNewOperation) {
    shape.someNewOperation()
  } else {
    defaultSomeNewOperation(shape)
  }
}
3
  • @ntohl In tests I've done (on Java 8, note that test used Java 6) instanceof was faster, so I guess the speed of relative speed of the two must vary based upon subtle details.
    – Andy
    Aug 4, 2015 at 16:59
  • Sorry. Not buying it. In a typical visitor pattern there are 2 calls on the stack. The caller calls class.accept(visitor), and then the accept method calls visitor.visitClass(this). At this point, the visitor is doing the logic. Using instanceOf may or may not be a fast call, when compared to a single call to the visitor. But the problem you are introducing is bloat. If you have 50 classes in your hierarchy, you will make 49 wasted calls to instanceOf when you want to get to the last class in your massive if-else block. I can't see how that out performs the Visitor. Oct 26, 2023 at 1:03
  • @PaulRouleau yeah if there are that many classes I agree the visitor pattern is better, as long as there are no issues like needing to allow 3rd-party code to define its own subclasses. But I think there are a lot of cases that need only a half-dozen classes, in which case the flexibility of instanceof can be worth it
    – Andy
    Oct 26, 2023 at 6:09
0

I think you are talking about the 'Expression problem'. See this link for more information about this problem. Object algebras are a great solution for this problem. It has been described in a paper called Extensibility for the masses - Practical Extensibility with Object Algebras. Object algebras are applicable to a wide range of programming languages that have basic support for generics.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.