Build a Flexible Validation Engine with Pluggable Rules
Data Structure DesignModel answerLast 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:
- Each validation check is independent and self-contained.
- New checks can be registered with the engine without modifying its logic.
- The engine runs all registered checks against an employee record and collects every violation.
- Rules can specify a priority so critical checks run before advisory ones.
What to provide
- An
Employeedata structure holdingid,salary,hours_worked, andstate. - 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is to make the engine depend only on an abstraction, never on specific checks. Each validation becomes a strategy: a class implementing a common interface with one method, validate(employee), that returns a list of violations. The engine holds a collection of these strategies and iterates through them. It doesn't know or care what kind of check it's running—it just calls validate on each one.
This design follows the Open/Closed Principle: you extend behavior by writing new check classes and registering them. The engine itself never changes.
Three supporting decisions complete the picture:
Priority ordering. Each check carries a priority integer (lower values run first). The engine maintains checks in sorted order by (priority, insertion_sequence). This means ties preserve registration order, and the sorting cost is paid once at registration rather than on every validation run.
Composite pattern. A special CompositeRule is itself a check that contains child checks. This lets you bundle "California compliance" into one block with one priority. The engine treats it like any other check; no special-case logic needed.
Structured violations. Each violation records the check name, employee ID, a message, and a severity level. Severity provides a hook for short-circuiting (stop after the first critical violation) and for downstream reporting.
Why this works
- Every check runs in priority order. The check list stays sorted on insert.
validate()walks it once and concatenates all violations. The output is the union of all rule violations, ordered by check priority. - Checks don't interfere. Each check only reads the
Employeeobject, which is immutable. One check can't affect another's result. - Ordering is deterministic. We sort by
(priority, sequence_number)wheresequence_numberis a unique counter. Two checks with the same priority retain insertion order. - Short-circuiting is optional. If you pass
stop_on_critical=True, the engine halts after the first check that produces a critical violation, but still returns everything collected so far. - Composites act like checks. A composite sorts its children the same way and returns their combined violations. The engine sees it as a single check.
Complexity
Let n be the number of checks and v the total violations found.
add_rule: O(log n) to find the insertion point plus O(n) to shift the list. Since rules are registered infrequently (usually at startup), this is acceptable.validate: O(sum of each check's cost). If each check runs in constant time, this is O(n). No sorting happens during validation.- Space: O(n) for checks, O(v) for violations.
Edge cases
- No checks registered: returns an empty list.
- Equal priorities: insertion order is preserved.
- Boundary values: exactly
limithours or exactlyminimumsalary passes. Use strict inequalities (>and<). - Check raises an exception: the engine catches it and records it as a violation for that check, rather than crashing the entire batch. A payroll run over thousands of employees shouldn't fail because one check has a bug.
- Invalid configuration (negative
limit): raiseValueErrorimmediately when the check is created. - Unknown state in regional checks: fall back to a configurable default minimum.
- Non-check passed to
add_rule: raiseTypeError.
Implementation
from __future__ import annotations
import bisect
import itertools
from abc import ABC, abstractmethod
from dataclasses import dataclass
from enum import IntEnum
from typing import Iterable
class Severity(IntEnum):
WARNING = 1
ERROR = 2
CRITICAL = 3
@dataclass(frozen=True)
class Employee:
id: int
salary: float
hours_worked: float
state: str
@dataclass(frozen=True)
class Violation:
check: str
employee_id: int
message: str
severity: Severity = Severity.ERROR
class Check(ABC):
"""Base abstraction for validation strategies. Lower priority runs first."""
def __init__(self, priority: int = 100, severity: Severity = Severity.ERROR):
self.priority = priority
self.severity = severity
@property
def name(self) -> str:
return type(self).__name__
@abstractmethod
def validate(self, employee: Employee) -> list[Violation]:
"""Return list of violations, or empty list if valid."""
pass
def _violation(self, employee: Employee, message: str) -> Violation:
return Violation(self.name, employee.id, message, self.severity)
class HoursCapRule(Check):
def __init__(self, limit: float, **kwargs):
super().__init__(**kwargs)
if limit <= 0:
raise ValueError("limit must be positive")
self.limit = limit
def validate(self, employee: Employee) -> list[Violation]:
if employee.hours_worked > self.limit:
return [self._violation(
employee,
f"hours {employee.hours_worked} exceeds cap {self.limit}",
)]
return []
class SalaryFloorRule(Check):
def __init__(self, minimum: float, **kwargs):
super().__init__(**kwargs)
if minimum < 0:
raise ValueError("minimum cannot be negative")
self.minimum = minimum
def validate(self, employee: Employee) -> list[Violation]:
if employee.salary < self.minimum:
return [self._violation(
employee,
f"salary {employee.salary} below floor {self.minimum}",
)]
return []
class StateSalaryRule(Check):
def __init__(self, floors: dict[str, float], default: float = 0.0, **kwargs):
super().__init__(**kwargs)
self.floors = dict(floors)
self.default = default
def validate(self, employee: Employee) -> list[Violation]:
floor = self.floors.get(employee.state, self.default)
if employee.salary < floor:
return [self._violation(
employee,
f"salary {employee.salary} below {employee.state} floor {floor}",
)]
return []
class _OrderedChecks:
"""Maintains checks sorted by (priority, insertion order)."""
def __init__(self) -> None:
self._items: list[tuple[int, int, Check]] = []
self._counter = itertools.count()
def add(self, check: Check) -> None:
if not isinstance(check, Check):
raise TypeError(f"expected Check, got {type(check).__name__}")
bisect.insort(self._items, (check.priority, next(self._counter), check))
def __iter__(self):
return (check for _, _, check in self._items)
def __len__(self) -> int:
return len(self._items)
class CompositeRule(Check):
"""Groups multiple checks into one logical unit."""
def __init__(self, checks: Iterable[Check] = (), label: str | None = None, **kwargs):
super().__init__(**kwargs)
self._children = _OrderedChecks()
self._label = label
for check in checks:
self.add_rule(check)
@property
def name(self) -> str:
return self._label if self._label else super().name
def add_rule(self, check: Check) -> None:
self._children.add(check)
def validate(self, employee: Employee) -> list[Violation]:
violations = []
for check in self._children:
violations.extend(check.validate(employee))
return violations
class RuleEngine:
"""Central validator that runs registered checks in priority order."""
def __init__(self, stop_on_critical: bool = False):
self._checks = _OrderedChecks()
self._stop_on_critical = stop_on_critical
def add_rule(self, check: Check) -> None:
self._checks.add(check)
def validate(self, employee: Employee) -> list[Violation]:
violations = []
for check in self._checks:
try:
result = check.validate(employee)
violations.extend(result)
if self._stop_on_critical and any(v.severity == Severity.CRITICAL for v in result):
break
except Exception as e:
violations.append(Violation(
check=check.name,
employee_id=employee.id,
message=f"check failed: {e}",
severity=Severity.ERROR,
))
return violations
# Example usage
if __name__ == "__main__":
employee = Employee(id=42, salary=55000, hours_worked=48, state="NY")
engine = RuleEngine()
engine.add_rule(HoursCapRule(limit=45))
engine.add_rule(SalaryFloorRule(minimum=30000))
engine.add_rule(StateSalaryRule(floors={"CA": 64000, "NY": 58240}))
violations = engine.validate(employee)
for v in violations:
print(f"[{v.severity.name}] {v.check}: {v.message}")
Common mistakes
- Hard-coding checks in the engine. Using
if isinstance(rule, HoursCapRule)defeats the whole purpose. The engine should only know about the base abstraction. - Re-sorting on every validation. If you have 100 checks and validate 10,000 employees, you'll sort 1,000,000 times. Sort once when checks are added.
- Ignoring exceptions. A single bad check shouldn't crash the entire validation run. Catch exceptions and report them as violations.
- Mutable Employee. If checks can modify the employee, later checks see altered data and results become unpredictable. Make it immutable.
- No priority ties policy. If two checks have the same priority and you don't track insertion order, the execution sequence becomes non-deterministic and tests become flaky.