THN Interview Prep

Interpreter (Behavioral)

Intent / problem it solves

Given a language (grammar), represent sentences as an abstract syntax tree and interpret them. Useful for small DSLs, rules engines, or expression evaluation.

When to use / when NOT

Use for narrow, stable grammars with simple composition rules (boolean expressions, filters).

Avoid for full programming languages (use a parser generator), or when a rule table or external engine is simpler.

Structure

Abstract expression declares interpret(context); terminal and nonterminal expressions compose recursively.

Loading diagram…

Go example

package main

import "fmt"

type Context struct {
	variables map[string]int
}

type Expression interface {
	Evaluate(ctx Context) int
}

type NumberLiteral struct{ Value int }

func (literal NumberLiteral) Evaluate(ctx Context) int { return literal.Value }

type Variable struct{ Name string }

func (variable Variable) Evaluate(ctx Context) int {
	return ctx.variables[variable.Name]
}

type Add struct {
	Left  Expression
	Right Expression
}

func (add Add) Evaluate(ctx Context) int {
	return add.Left.Evaluate(ctx) + add.Right.Evaluate(ctx)
}

func main() {
	ctx := Context{variables: map[string]int{"count": 5}}
	tree := Add{Left: Variable{Name: "count"}, Right: NumberLiteral{Value: 3}}
	fmt.Println(tree.Evaluate(ctx))
}

JavaScript example

class QueryContext {
  constructor(fields) {
    this.fields = fields;
  }
}

class EqualsExpr {
  constructor(fieldName, expected) {
    this.fieldName = fieldName;
    this.expected = expected;
  }

  interpret(context) {
    return context.fields[this.fieldName] === this.expected;
  }
}

class AndExpr {
  constructor(left, right) {
    this.left = left;
    this.right = right;
  }

  interpret(context) {
    return this.left.interpret(context) && this.right.interpret(context);
  }
}

const rule = new AndExpr(
  new EqualsExpr('role', 'admin'),
  new EqualsExpr('region', 'eu'),
);

console.log(rule.interpret(new QueryContext({ role: 'admin', region: 'eu' })));

Interview phrase

“Interpreter models a tiny grammar as composable objects; it shines for rule DSLs and dies when the grammar grows—then I switch to a parser or external evaluator.”

Connect to LLD for query builders, spreadsheet formulas, or policy engines in LLD case studies.

Last updated on

Spotted something unclear or wrong on this page?

On this page