CS FundamentalsVery hardProduct-company design interview

A compiler has a stable set of AST node classes (Number, BinaryOp, Call, Variable) but keeps adding new operations: type-check, pretty-print, optimise, generate code. Which pattern fits, and what is its main drawback?

  1. A. Strategy; each operation becomes a separate algorithm, but nodes cannot be reused
  2. B. Template Method; new operations are easy but new node types need a new template
  3. C. Composite; it makes trees easy, but every new operation still edits every node
  4. D. Visitor; new operations are added without touching the node classes, but adding a new node type forces a change to every visitor

Correct answer: D. Visitor; new operations are added without touching the node classes, but adding a new node type forces a change to every visitor

Visitor uses double dispatch so each operation lives in one visitor class. That suits a stable element hierarchy with growing operations; the trade-off is that a new element type needs a new visit method in all visitors.

More Software Engineering, Git and Cloud Basics questions

Exams that ask this topic