LLD Dojo

Interpreter

Rare. Named in books and almost never wanted in an interview. Read once so the word does not surprise you, then move on.

Start with the problem

Suppose a rule engine has to evaluate conditions supplied at runtime, not written into Java source: "vehicle type is TRUCK and stay is over four hours." The classic move is to model the grammar as a tree of objects, one class per kind of expression, each holding an interpret() method. The tree gets built once, from whatever format the rule arrived in.

sealed interface Expression permits Constant, VehicleTypeIs, StayOver, And {}
record Constant(boolean value) implements Expression {}
record VehicleTypeIs(VehicleType type) implements Expression {}
record StayOver(Duration threshold) implements Expression {}
record And(Expression left, Expression right) implements Expression {}

boolean evaluate(Expression expr, Vehicle vehicle, Duration stay) {
    return switch (expr) {
        case Constant c -> c.value();
        case VehicleTypeIs v -> vehicle.type() == v.type();
        case StayOver s -> stay.compareTo(s.threshold()) > 0;
        case And a -> evaluate(a.left(), vehicle, stay) && evaluate(a.right(), vehicle, stay);
    };
}

This is Interpreter's shape: a grammar represented as a type per rule, and something that walks the tree to produce an answer. GoF puts the walk as an interpret() method on every node. The sealed and switch version above puts it in one function instead, for the exhaustiveness reasons visitor.md already covers.

What modern Java changes here

The story is the same as Visitor's. Sealed interfaces and pattern-matching switch replace one method per node with one function per operation. The textbook shape, an interpret() method on every node, is rarely how anyone writes this in Java 21, even when what they are doing is exactly what Interpreter describes.

When naming it is wrong

Nearly always, in an LLD interview. Interpreter is for building a small language: a rule engine's condition syntax, a query filter, a template engine. Most LLD problems, a parking lot, a rate limiter, an elevator, never ask anyone to parse anything. If a round does hand over a rule described as data, the sealed hierarchy above is worth reaching for. Naming it Interpreter out loud buys nothing an interviewer is listening for.

Where this lives in the app

The anchor for this page is null, on purpose, and that is the fact worth stating plainly. No problem in this app's corpus, not the parking lot, the vending machine, the elevator, the rate limiter, or any other, asks for a grammar to be represented and evaluated. The rule-engine example above was built for this page and does not exist anywhere in the corpus.

All reference pages