Skip to content

Visitor Pattern: Add Operations Without Editing Your Classes

Learn the Visitor pattern: how double dispatch lets you add new operations over a stable object structure without modifying its classes.

12 min readDesign patternBehavioural

Represent an operation to be performed on the elements of an object structure as a separate object, so you can define new operations without changing the classes of the elements it works on.

Visitor answers one question: what do you do when the set of object types is fixed, but the list of things you want to do with them keeps growing? Instead of adding one more method to every class each time, you move each operation into its own visitor object. The classes only need a single accept method that hands themselves to the visitor. In this guide you follow one invented invoicing product through the whole pattern: the problem, the structure, pseudocode and runnable code in TypeScript, Python and PHP. You also get the trade-offs and the interview questions that usually come with it, especially double dispatch and why Visitor makes adding new element types painful.

The problem

A situation where the obvious design starts to hurt.

Tallyhouse is an invoicing app used by about 3,000 small businesses. Every invoice is a list of lines, and there are exactly three kinds: a ProductLine (SKU, quantity, unit price), a ServiceLine (description, hours, hourly rate) and a DiscountLine (promo code, fixed amount). Those three classes have not changed in two years and are owned by the core billing team.

The finance squad, three engineers, keeps asking for new operations over invoices. First it was tax calculation: products taxed at 20%, services at 10%, and discounts reducing the product tax base. Then a CSV export for accountants. Next quarter they want an audit check and a revenue-recognition report.

The first approach was to add calculateTax() and toCsvRow() to all three line classes. Each new feature meant a pull request against code another team owns, the line classes started mixing pricing, tax law and file formats, and the billing team now reviews finance logic they do not understand.

The second approach was worse: a function per feature that loops over lines and switches on instanceof. Those switches got copied into four places, and when one forgot the discount branch, a batch of 212 invoices was exported with the wrong totals. Nothing warned anyone that a case was missing.

The solution

What the pattern proposes.

Turn each operation into a visitor class. Define an InvoiceLineVisitor interface with one method per line type: visitProduct, visitService, visitDiscount. Tax calculation becomes TaxVisitor; the accountant export becomes CsvExportVisitor. Each keeps whatever state it needs, such as a running tax total or a list of CSV rows.

The line classes get exactly one new method, accept(visitor), and it does nothing but call the matching visit method with itself: ProductLine.accept calls visitor.visitProduct(this). This is double dispatch: the first call picks the line's own accept based on the line's runtime type, the second picks the visitor's method based on which visitor you passed. The right code runs for each combination without any type switch.

Invoice is the object structure. Its accept walks its lines and passes the same visitor to each one, so a single pass collects the full result.

From now on, when finance asks for an audit check, they write AuditVisitor in their own module. The billing team's classes do not change. And because the visitor interface lists every line type, a visitor that forgets visitDiscount fails to compile in TypeScript and PHP, or to instantiate in Python, instead of silently producing wrong totals.

An everyday analogy

The same idea, outside software.

Think of the folder of paperwork a household keeps: pay slips, utility bills, bank statements. The documents never change shape. In spring a tax preparer goes through the folder, in summer a mortgage broker does, and in December you go through it yourself to plan next year's budget.

Each person knows what to do with each kind of document: the tax preparer cares about deductions on bills, the broker about income on pay slips. The documents do not learn tax law or lending rules. They just present themselves: this is a pay slip, here are my numbers. When a new kind of reviewer shows up, nobody rewrites the documents; you just hand the folder to someone new. But if a brand-new type of document appears, every reviewer has to learn how to read it.

Structure

The pieces and how they relate.

Tallyhouse invoice lines accept visitors; each visitor implements one operation for every line type.BillingJob creates TaxVisitor. BillingJob creates CsvExportVisitor. BillingJob calls Invoice (accept(visitor)). TaxVisitor implements InvoiceLineVisitor. CsvExportVisitor implements InvoiceLineVisitor. Invoice has a InvoiceLine (lines). ProductLine implements InvoiceLine. ServiceLine implements InvoiceLine. DiscountLine implements InvoiceLine. InvoiceLine calls InvoiceLineVisitor (visitX(this)).BillingJobruns tax and export«interface»InvoiceLineVisitorvisitProduct /visitService …TaxVisitortotalCentsCsvExportVisitorrows, toCsv()Invoiceaccept(visitor)loops lines«interface»InvoiceLineaccept(visitor)ProductLinesku, quantity,unitPriceCentsServiceLinedescription, hours,hourlyRateCentsDiscountLinecode, amountCentsDouble dispatchaccept(v) callsv.visitProduct(this)accept(visitor)linesvisitX(this)
Tallyhouse invoice lines accept visitors; each visitor implements one operation for every line type.

Participants

Visitor (InvoiceLineVisitor)
Declares one visit method per concrete element type. Its method list is the contract every operation must fulfil.
Concrete visitors (TaxVisitor, CsvExportVisitor)
Each implements one operation across all element types and holds the state that operation accumulates, such as a running tax total or exported rows.
Element (InvoiceLine)
Declares accept(visitor), the single hook that lets any visitor reach the element.
Concrete elements (ProductLine, ServiceLine, DiscountLine)
Implement accept by calling the visit method that matches their own type, passing themselves. They expose the data visitors need.
Object structure (Invoice)
Owns the elements and walks them, passing the same visitor to each so one traversal produces a complete result.
Client (BillingJob)
Creates the visitor it needs, hands it to the structure and reads the result afterwards.

Pseudocode

The solution to the scenario, language-neutral.

interface InvoiceLineVisitor
  visitProduct(line: ProductLine)
  visitService(line: ServiceLine)
  visitDiscount(line: DiscountLine)

interface InvoiceLine
  accept(visitor: InvoiceLineVisitor)

class ProductLine implements InvoiceLine
  fields sku, quantity, unitPriceCents
  accept(visitor): visitor.visitProduct(this)

class ServiceLine implements InvoiceLine
  fields description, hours, hourlyRateCents
  accept(visitor): visitor.visitService(this)

class DiscountLine implements InvoiceLine
  fields code, amountCents
  accept(visitor): visitor.visitDiscount(this)

class Invoice
  fields number, lines
  accept(visitor)
    for each line in lines
      line.accept(visitor)

class TaxVisitor implements InvoiceLineVisitor
  totalCents = 0
  visitProduct(line):  totalCents += floor(line.quantity * line.unitPriceCents * 20 / 100)
  visitService(line):  totalCents += floor(line.hours * line.hourlyRateCents * 10 / 100)
  visitDiscount(line): totalCents -= floor(line.amountCents * 20 / 100)

class CsvExportVisitor implements InvoiceLineVisitor
  rows = ["type,ref,qty,amount_cents"]
  visitProduct(line):  rows.add("product," + sku + "," + quantity + "," + quantity * unitPriceCents)
  visitService(line):  rows.add("service," + description + "," + hours + "," + hours * hourlyRateCents)
  visitDiscount(line): rows.add("discount," + code + ",1,-" + amountCents)
  toCsv(): join rows with newline

// BillingJob
invoice = Invoice("INV-2041", [ProductLine("SKU-114", 3, 1500), ServiceLine("setup", 2, 8000), DiscountLine("SPRING5", 500)])
tax = TaxVisitor(); invoice.accept(tax)        // tax.totalCents == 2400
csv = CsvExportVisitor(); invoice.accept(csv)  // four CSV rows

The code

The same solution in TypeScript, Python and PHP.

interface InvoiceLineVisitor {
  visitProduct(line: ProductLine): void;
  visitService(line: ServiceLine): void;
  visitDiscount(line: DiscountLine): void;
}

interface InvoiceLine {
  accept(visitor: InvoiceLineVisitor): void;
}

class ProductLine implements InvoiceLine {
  constructor(
    readonly sku: string,
    readonly quantity: number,
    readonly unitPriceCents: number,
  ) {}

  accept(visitor: InvoiceLineVisitor): void {
    visitor.visitProduct(this);
  }
}

class ServiceLine implements InvoiceLine {
  constructor(
    readonly description: string,
    readonly hours: number,
    readonly hourlyRateCents: number,
  ) {}

  accept(visitor: InvoiceLineVisitor): void {
    visitor.visitService(this);
  }
}

class DiscountLine implements InvoiceLine {
  constructor(
    readonly code: string,
    readonly amountCents: number,
  ) {}

  accept(visitor: InvoiceLineVisitor): void {
    visitor.visitDiscount(this);
  }
}

class Invoice {
  constructor(
    readonly number: string,
    private readonly lines: InvoiceLine[],
  ) {}

  accept(visitor: InvoiceLineVisitor): void {
    for (const line of this.lines) {
      line.accept(visitor);
    }
  }
}

class TaxVisitor implements InvoiceLineVisitor {
  totalCents = 0;

  visitProduct(line: ProductLine): void {
    this.totalCents += Math.floor((line.quantity * line.unitPriceCents * 20) / 100);
  }

  visitService(line: ServiceLine): void {
    this.totalCents += Math.floor((line.hours * line.hourlyRateCents * 10) / 100);
  }

  visitDiscount(line: DiscountLine): void {
    this.totalCents -= Math.floor((line.amountCents * 20) / 100);
  }
}

class CsvExportVisitor implements InvoiceLineVisitor {
  private readonly rows: string[] = ["type,ref,qty,amount_cents"];

  visitProduct(line: ProductLine): void {
    this.rows.push(`product,${line.sku},${line.quantity},${line.quantity * line.unitPriceCents}`);
  }

  visitService(line: ServiceLine): void {
    this.rows.push(`service,${line.description},${line.hours},${line.hours * line.hourlyRateCents}`);
  }

  visitDiscount(line: DiscountLine): void {
    this.rows.push(`discount,${line.code},1,-${line.amountCents}`);
  }

  toCsv(): string {
    return this.rows.join("\n");
  }
}

const invoice = new Invoice("INV-2041", [
  new ProductLine("SKU-114", 3, 1500),
  new ServiceLine("setup", 2, 8000),
  new DiscountLine("SPRING5", 500),
]);

const tax = new TaxVisitor();
invoice.accept(tax);
console.log(`Tax for ${invoice.number}: ${tax.totalCents} cents`); // 2400

const csv = new CsvExportVisitor();
invoice.accept(csv);
console.log(csv.toCsv());

When to use it

Situations where it pays off.

  • The set of element classes is stable, but you keep adding operations over them.

    Visitor makes the cheap change the frequent one. A new operation is one new class; the element classes stay untouched. If element types change more often than operations, the trade-off flips against you.

  • Many unrelated operations would otherwise pollute the element classes.

    Tax rules, file formats and audit logic do not belong in a data class owned by another team. Each visitor keeps one concern together in one place.

  • You have type switches over the same hierarchy repeated in several places.

    Replacing each switch with a visitor gives you compiler-checked exhaustiveness: forgetting a case becomes a build error instead of a silent bug.

  • An operation needs to accumulate state while walking a structure, such as a tree or a document.

    The visitor object is a natural home for running totals, collected rows or error lists, and the structure handles traversal once for every operation.

  • You cannot or should not modify the element classes beyond a single hook.

    After adding accept once, the classes are closed for modification while the set of operations stays open.

How to implement it

Steps to introduce it in existing code.

  1. Check the direction of change first. List the element types and the operations you expect over the next year. If types are fixed and operations grow, Visitor fits.

  2. Declare the visitor interface with one method per concrete element type, named after the type, such as visitProduct and visitService.

  3. Add accept(visitor) to the element interface and implement it in every concrete element by calling the matching visit method with this.

  4. Make the object structure, here Invoice, expose accept and forward the visitor to each element it contains, so clients do not write the loop.

  5. Move each existing operation into a concrete visitor. Give the visitor fields for the state it accumulates and a method to read the result.

  6. Expose on the elements only the data visitors genuinely need, preferably read-only, so moving logic out does not force you to make everything mutable and public.

  7. Replace the old switch statements and per-class methods with calls like invoice.accept(new TaxVisitor()), then delete the dead code.

Pros and cons

What you gain and what you pay.

Pros

  • Open/Closed for operations: adding an audit report or a new export is one new class, with no edits to the line classes.
  • Each operation lives in one place instead of being spread across every element class.
  • Exhaustiveness is enforced by the visitor interface, so a missing case is caught by the compiler or at instantiation.
  • Visitors can accumulate state across a whole traversal without global variables or extra parameters threaded through calls.
  • Element classes stay small and focused on their data, and teams can own operations independently of the model.

Cons

  • Adding a new element type is expensive: every existing visitor must get a new method, which is exactly the shotgun surgery Visitor avoids for operations.
  • Visitors often need access to element internals, which pushes you to expose fields you would otherwise keep private.
  • The double dispatch indirection is harder to read and debug than a direct method call, especially for newcomers.
  • It adds boilerplate: an interface, an accept per class and a method per type in every visitor, which is overkill for two operations on two types.

Relations with other guides

Patterns it's often confused or combined with.

Common questions

Short answers to the usual doubts.

What is double dispatch, and why does Visitor need it?

Most mainstream languages pick a method based on the runtime type of one object, the receiver. Visitor needs the behaviour to depend on two types: the element and the operation. It gets there with two calls. line.accept(visitor) dispatches on the line's type, and inside it visitor.visitProduct(this) dispatches on the visitor's type. Together they select the right code for each pair without any type checks.

Why not just overload a single visit method instead of naming them visitProduct, visitService and so on?

Overload resolution in languages like Java or C# happens at compile time on the static type. If you hold an InvoiceLine and call visitor.visit(line), the compiler cannot pick the ProductLine overload. Overloading only works inside accept, where this has the concrete type. Distinct names avoid that confusion and work in TypeScript, Python and PHP, which have no method overloading.

What happens when Tallyhouse adds a fourth line type, like a shipping line?

You add visitShipping to the visitor interface, and every existing visitor must implement it. That is the deliberate cost of the pattern: operations are cheap to add, element types are expensive. The upside is that the compiler or the abstract base class lists every visitor you need to update, so nothing is silently skipped.

Do I still need Visitor in languages with pattern matching?

Not always. With sealed or union types and exhaustive matching, such as a TypeScript discriminated union with a never check, you get the same compiler-checked exhaustiveness with less code. Visitor still earns its place when you want classic class hierarchies, when operations carry significant state, or when the language cannot check exhaustiveness for you.

How would you explain when to use Visitor in an interview?

Frame it as the direction of change. If the set of types is stable and operations keep growing, Visitor puts each operation in one class and leaves the types closed. If types grow and operations are stable, put methods on the types instead. Mention double dispatch, the cost of adding a new element type and the encapsulation trade-off, and you have covered what interviewers usually probe.