AlgoViz

Visitor pattern

hard 55 min

Visitor moves an operation on a family of classes into an object of its own.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:34

See it run

Two calls, two types: the element says what it is, the visitor does the work.

Operations

Export to HTML

A document of three parts and one visitor. Follow the two calls per part.

Step 1 of 8

The visitor arrives

docDocumentparagraphParagraphtextTea & milkimageImageurllogo.pngtableTablesize2 by 2htmlHtmlExportparts0lastnone

The document got an empty HtmlExport.

Step 1: The visitor arrives

class Document:    def accept(self, v):        for e in self._elements:            e.accept(v)class Paragraph:    def accept(self, v):        v.visit_paragraph(self)class HtmlExport:    def visit_paragraph(self, p):        self._out.append(f"<p>{escape(p.text)}</p>")
Watch
accept, visit
Result
Three tags

Nobody asks for a type.

In the real world

The same visitor pattern doing real jobs. Pick one and step through it.

A walker leads a visitor through a small document.

Step 1 of 4

Enter doc

walkerWalkeroutlineVisitorpathdoclastenter docdocNodeintroNodeprivateNodesecretNodeenter(doc)

The path is doc.

Step 1: Enter doc

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • A copied accept

    critical

    Images are exported as paragraphs.

    Wrong
    class Image:    def accept(self, v):        v.visit_paragraph(self)
    Right
    class Image:    def accept(self, v):        v.visit_image(self)
  • accept in the base class

    major

    With overloads the base type is chosen.

    Wrong
    abstract class Element {  void accept(Visitor v) { v.visit(this); }}
    Right
    class Image extends Element {  void accept(Visitor v) { v.visit(this); }}
  • A reused visitor

    major

    The old result is still inside.

    Wrong
    html = HtmlExport()for doc in docs:    doc.accept(html)
    Right
    for doc in docs:    html = HtmlExport()    doc.accept(html)
  • A silent default

    critical

    New elements vanish from the export.

    Wrong
    def visit_default(self, e):    pass
    Right
    def visit_default(self, e):    raise NotImplementedError(type(e))
  • Text without escaping

    critical

    A script in a paragraph runs.

    Wrong
    out.append(f"<p>{p.text}</p>")
    Right
    out.append(f"<p>{escape(p.text)}</p>")
  • Type checks inside a visitor

    major

    The question the pattern removed is back.

    Wrong
    def visit(self, e):    if isinstance(e, Image): ...
    Right
    def visit_image(self, i): ...

Interview tips

  • Draw the grid

    • Types down.
    • Operations across.
    • Which side grows?
  • Two handshakes

    • accept: I am an image.
    • visit: I am HTML.
    • No type checks.
  • Mind the state

    • Collecting: one per run.
    • Returning: share freely.
    • Elements immutable.
  • Know the neighbours

    • Sealed and switch.
    • Methods in classes.
    • singledispatch.