CS FundamentalsHardHCL · Tech Mahindra pattern

A parser builds an abstract syntax tree where each node type (NumberNode, AddNode, MulNode) implements its own evaluate() method directly on the node class. A new requirement asks for a pretty-printer operation on the same tree without modifying the node classes. Which refactor best enables this, and what does it cost?

  1. A. Refactor to the Visitor pattern: add an accept(visitor) method to each node and move evaluate()/print() logic into separate Visitor classes — new operations are now added without touching node classes, but every visitor must still handle every node type
  2. B. Add a print() method directly to each node class; this requires no new pattern and has no downsides
  3. C. Switch to the Decorator pattern, wrapping each node to add printing behaviour
  4. D. Use the Singleton pattern so there is only one node of each type

Correct answer: A. Refactor to the Visitor pattern: add an accept(visitor) method to each node and move evaluate()/print() logic into separate Visitor classes — new operations are now added without touching node classes, but every visitor must still handle every node type

This is exactly the scenario Visitor targets: operations (evaluate, print) are pulled out of the element classes into visitor classes, so adding an operation needs no change to node classes — the Open/Closed trade-off is that adding a new node type instead requires updating every visitor.

More Software Engineering, Git and Cloud Basics questions

Exams that ask this topic