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?
- 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
- B. Add a print() method directly to each node class; this requires no new pattern and has no downsides
- C. Switch to the Decorator pattern, wrapping each node to add printing behaviour
- 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.
Practise more Software Engineering, Git and Cloud Basics questionsSoftware Engineering, Git and Cloud Basics: notes and key points
More Software Engineering, Git and Cloud Basics questions
- A notification system has a base Notifier.send(message) and wrappers SMSDecorator, SlackDecorator that each wrap a Notifier and add their…
- A spreadsheet's Cell objects can contain other Cells (a range), and client code calls cell.getValue() uniformly whether cell is a single…
- A rendering engine has a Shape hierarchy (Circle, Square) and a separate Renderer hierarchy (VectorRenderer, RasterRenderer), and any…
- A text editor needs to support thousands of on-screen Character objects efficiently. Most of a Character's data (font, size, color) is…
- A rule says: a loan is approved only if (credit score >= 700) AND (income >= 50000) AND (no existing default). Using a decision table that…
- A password field must be 8–20 characters long. Using boundary value analysis on this single range, which set of test lengths is the…