KatInterview

Build a Flexible Validation Engine with Pluggable Rules

Data Structure DesignModel answer
MediumModel answerData Structure Designobject-oriented-designdesign-patternsextensibility

Last updated

Design a payroll validator that lets you plug in new checks without changing the core engine, using abstraction and priority-based execution.

You're building a validation framework for a payroll application. The system checks employee records against business rules—things like "hours cannot exceed 50 per week" or "salary must meet the state minimum." New rules appear frequently as regulations change, and you need a way to add them without rewriting the validator itself.

Your task is to design a system where:

  1. Each validation check is independent and self-contained.
  2. New checks can be registered with the engine without modifying its logic.
  3. The engine runs all registered checks against an employee record and collects every violation.
  4. Rules can specify a priority so critical checks run before advisory ones.

What to provide

  • An Employee data structure holding id, salary, hours_worked, and state.
  • A base abstraction for validation checks.
  • A central validator that accepts checks, runs them in priority order, and returns violations.
  • At least two concrete check implementations (e.g., overtime cap, salary floor).
  • A way to combine multiple checks into a single logical unit that can be registered as one.

Example behavior

employee = Employee(id=42, salary=55000, hours_worked=48, state="NY")

validator = RuleEngine()
validator.add_rule(HoursCapRule(limit=45))
validator.add_rule(SalaryFloorRule(minimum=30000))

violations = validator.validate(employee)
# violations contains one entry: hours 48 exceeds limit 45

Considerations

  • The engine should work with any number of checks.
  • Checks may need configuration (like limit=45) when created.
  • Think about how you'd handle execution order when some checks are more important than others.
  • Consider how the engine should behave if a check throws an exception.

Hints

Hint 1

Each check should be a separate class implementing a common interface with a single validation method.

Hint 2

Store checks in sorted order by priority so validation runs them front-to-back without re-sorting every time.

Hint 3

Use a composite pattern to group related checks into one unit the engine can treat like any other check.