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.
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
acceptby 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 rowsThe 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());from __future__ import annotations
from abc import ABC, abstractmethod
from dataclasses import dataclass
class InvoiceLineVisitor(ABC):
@abstractmethod
def visit_product(self, line: ProductLine) -> None: ...
@abstractmethod
def visit_service(self, line: ServiceLine) -> None: ...
@abstractmethod
def visit_discount(self, line: DiscountLine) -> None: ...
class InvoiceLine(ABC):
@abstractmethod
def accept(self, visitor: InvoiceLineVisitor) -> None: ...
@dataclass(frozen=True)
class ProductLine(InvoiceLine):
sku: str
quantity: int
unit_price_cents: int
def accept(self, visitor: InvoiceLineVisitor) -> None:
visitor.visit_product(self)
@dataclass(frozen=True)
class ServiceLine(InvoiceLine):
description: str
hours: int
hourly_rate_cents: int
def accept(self, visitor: InvoiceLineVisitor) -> None:
visitor.visit_service(self)
@dataclass(frozen=True)
class DiscountLine(InvoiceLine):
code: str
amount_cents: int
def accept(self, visitor: InvoiceLineVisitor) -> None:
visitor.visit_discount(self)
class Invoice:
def __init__(self, number: str, lines: list[InvoiceLine]) -> None:
self.number = number
self._lines = list(lines)
def accept(self, visitor: InvoiceLineVisitor) -> None:
for line in self._lines:
line.accept(visitor)
class TaxVisitor(InvoiceLineVisitor):
def __init__(self) -> None:
self.total_cents = 0
def visit_product(self, line: ProductLine) -> None:
self.total_cents += line.quantity * line.unit_price_cents * 20 // 100
def visit_service(self, line: ServiceLine) -> None:
self.total_cents += line.hours * line.hourly_rate_cents * 10 // 100
def visit_discount(self, line: DiscountLine) -> None:
self.total_cents -= line.amount_cents * 20 // 100
class CsvExportVisitor(InvoiceLineVisitor):
def __init__(self) -> None:
self._rows = ["type,ref,qty,amount_cents"]
def visit_product(self, line: ProductLine) -> None:
self._rows.append(
f"product,{line.sku},{line.quantity},{line.quantity * line.unit_price_cents}"
)
def visit_service(self, line: ServiceLine) -> None:
self._rows.append(
f"service,{line.description},{line.hours},{line.hours * line.hourly_rate_cents}"
)
def visit_discount(self, line: DiscountLine) -> None:
self._rows.append(f"discount,{line.code},1,-{line.amount_cents}")
def to_csv(self) -> str:
return "\n".join(self._rows)
if __name__ == "__main__":
invoice = Invoice(
"INV-2041",
[
ProductLine("SKU-114", 3, 1500),
ServiceLine("setup", 2, 8000),
DiscountLine("SPRING5", 500),
],
)
tax = TaxVisitor()
invoice.accept(tax)
print(f"Tax for {invoice.number}: {tax.total_cents} cents") # 2400
csv = CsvExportVisitor()
invoice.accept(csv)
print(csv.to_csv())<?php
declare(strict_types=1);
interface InvoiceLineVisitor
{
public function visitProduct(ProductLine $line): void;
public function visitService(ServiceLine $line): void;
public function visitDiscount(DiscountLine $line): void;
}
interface InvoiceLine
{
public function accept(InvoiceLineVisitor $visitor): void;
}
final class ProductLine implements InvoiceLine
{
public function __construct(
public readonly string $sku,
public readonly int $quantity,
public readonly int $unitPriceCents,
) {}
public function accept(InvoiceLineVisitor $visitor): void
{
$visitor->visitProduct($this);
}
}
final class ServiceLine implements InvoiceLine
{
public function __construct(
public readonly string $description,
public readonly int $hours,
public readonly int $hourlyRateCents,
) {}
public function accept(InvoiceLineVisitor $visitor): void
{
$visitor->visitService($this);
}
}
final class DiscountLine implements InvoiceLine
{
public function __construct(
public readonly string $code,
public readonly int $amountCents,
) {}
public function accept(InvoiceLineVisitor $visitor): void
{
$visitor->visitDiscount($this);
}
}
final class Invoice
{
/** @param InvoiceLine[] $lines */
public function __construct(
public readonly string $number,
private readonly array $lines,
) {}
public function accept(InvoiceLineVisitor $visitor): void
{
foreach ($this->lines as $line) {
$line->accept($visitor);
}
}
}
final class TaxVisitor implements InvoiceLineVisitor
{
public int $totalCents = 0;
public function visitProduct(ProductLine $line): void
{
$this->totalCents += intdiv($line->quantity * $line->unitPriceCents * 20, 100);
}
public function visitService(ServiceLine $line): void
{
$this->totalCents += intdiv($line->hours * $line->hourlyRateCents * 10, 100);
}
public function visitDiscount(DiscountLine $line): void
{
$this->totalCents -= intdiv($line->amountCents * 20, 100);
}
}
final class CsvExportVisitor implements InvoiceLineVisitor
{
/** @var string[] */
private array $rows = ['type,ref,qty,amount_cents'];
public function visitProduct(ProductLine $line): void
{
$this->rows[] = sprintf('product,%s,%d,%d', $line->sku, $line->quantity, $line->quantity * $line->unitPriceCents);
}
public function visitService(ServiceLine $line): void
{
$this->rows[] = sprintf('service,%s,%d,%d', $line->description, $line->hours, $line->hours * $line->hourlyRateCents);
}
public function visitDiscount(DiscountLine $line): void
{
$this->rows[] = sprintf('discount,%s,1,-%d', $line->code, $line->amountCents);
}
public function toCsv(): string
{
return implode("\n", $this->rows);
}
}
$invoice = new Invoice('INV-2041', [
new ProductLine('SKU-114', 3, 1500),
new ServiceLine('setup', 2, 8000),
new DiscountLine('SPRING5', 500),
]);
$tax = new TaxVisitor();
$invoice->accept($tax);
echo "Tax for {$invoice->number}: {$tax->totalCents} cents\n"; // 2400
$csv = new CsvExportVisitor();
$invoice->accept($csv);
echo $csv->toCsv() . "\n";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
acceptonce, the classes are closed for modification while the set of operations stays open.
How to implement it
Steps to introduce it in existing code.
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.
Declare the visitor interface with one method per concrete element type, named after the type, such as
visitProductandvisitService.Add
accept(visitor)to the element interface and implement it in every concrete element by calling the matching visit method withthis.Make the object structure, here
Invoice, exposeacceptand forward the visitor to each element it contains, so clients do not write the loop.Move each existing operation into a concrete visitor. Give the visitor fields for the state it accumulates and a method to read the result.
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.
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
acceptper 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.
- Composite Pattern: Treat Single Items and Groups Through One Interface
Visitor is often run over a Composite tree. The composite node's
acceptforwards the visitor to its children, so one operation covers the whole hierarchy. - Iterator Pattern: Walk Any Collection Without Knowing Its Shape
Iterator walks a structure without caring about element types; Visitor dispatches type-specific behaviour.
Invoice.acceptcombines them: it iterates, then lets each line dispatch. - Command Pattern: Turn Requests into Objects You Can Queue and Undo
Both wrap behaviour in an object. A Command performs one action on one receiver; a Visitor performs one operation across many element types.
- Strategy: swap the rule without touching who uses it
Strategy swaps one algorithm behind a single interface. Visitor is like a family of strategies, one per element type, selected through double dispatch.
- Repeated Switches: the same type-code switch scattered across a codebase
Repeated
instanceofswitches over the same hierarchy are the classic signal that a Visitor could replace them with checked, centralised operations. - Replace Conditional with Polymorphism: One Class per Case
That refactoring moves behaviour into the element classes. Visitor is the alternative when you want polymorphism but cannot or should not put the logic inside those classes.
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.