Design a Configurable Order Validator with DAG Dependencies
ByteDanceSoftware Engineer · Technical ScreenLast updated
This problem tests your ability to design a flexible, extensible rule-processing engine that handles sequential and interdependent validation logic.
Problem Statement
Design an OrderValidator system that checks if an incoming order is valid. An order is a dictionary of properties (e.g., item_id, price, user_id, timestamp).
Validation logic is composed of individual rules. Some rules depend on the outcome of others. For example, the PriceValidator should only run if the ItemAvailabilityValidator has already confirmed the item exists. If any rule fails, the validation process should stop and return the failure reason.
Requirements
- Define an interface for a
ValidatorRuleand a way to register dependencies between rules. - Implement a
validate(order)method that executes the rules in a valid order (topological sort). - Ensure the system is extensible so new rules can be added without modifying existing code (Open/Closed Principle).
Example
Rules:
A: Check if item exists.B: Check if price is positive (Depends onA).C: Check if order timestamp is not in the future (No dependencies).
Execution flow: Either (C -> A -> B) or (A -> C -> B) are valid topological orderings.
Constraints
- The system must detect circular dependencies during initialization.
- Each rule should return a boolean
is_validand an optionalerror_message. - Your solution should handle a list of rules provided at runtime.
class OrderValidator:
def add_rule(self, name, rule_func, dependencies=[]):
# Logic to register rules
pass
def validate(self, order):
# Logic to execute rules in order
pass
Hints
Hint 1
Represent the rules as nodes in a Directed Acyclic Graph (DAG) where edges represent dependencies.
Hint 2
Use Kahn's algorithm or Depth First Search (DFS) to determine the execution sequence and detect cycles during the initialization phase.
Hint 3
Consider using a 'Context' object to pass data between rules, allowing them to share pre-calculated results if needed.
Follow-up questions
- How would you optimize the validation process if some rules require expensive network calls (e.g., calling an external inventory service)?
- How would you implement a 'partial validation' mode where you want to collect all errors instead of stopping at the first failure?
- What changes are needed to support conditional rule execution, where a rule is only triggered if a previous rule returned a specific value?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.