KatInterview

Refactoring and Hardening a Driver Dispatch Service

Data Structure DesignModel answer
MediumModel answerData Structure Designrefactoringthread-safetyobject-oriented-design

Last updated

Identify anti-patterns in legacy dispatch assignment code, implement fixes, introduce domain types, and design for thread-safety.

You are tasked with reviewing and refactoring a legacy driver assignment module (DriverAssigner) that pairs nearby available delivery drivers with incoming orders.

The original legacy implementation contains several bugs, bad practices, and vulnerabilities to race conditions:

class driverAssigner:
    def __init__(self, drivers=[]):
        self.drivers = drivers

    def assign_driver(self, order):
        try:
            best = None
            for d in self.drivers:
                if d['active'] == True:
                    dist = abs(d['x'] - order['x']) + abs(d['y'] - order['y'])
                    if best == None or dist < best[1]:
                        best = (d, dist)
            best[0]['active'] = False
            return best[0]['id']
        except:
            return None

Requirements

  1. Code Audit & Analysis: Identify the key issues in the legacy code across code quality, software architecture, error handling, input validation, and concurrency.
  2. Refactor & Redesign: Rewrite the implementation in modern Python. Your refactored version must:
    • Use strongly typed value objects (e.g., dataclasses) for domain entities (Location, Driver).
    • Eliminate dangerous default arguments, global state leaks, and anti-patterns (such as bare exceptions).
    • Implement deterministic tie-breaking logic (e.g., break distance ties by driver ID).
    • Throw precise domain exceptions rather than swallowing errors.
  3. Thread Safety: Ensure all operations (assign_driver, add_driver, release_driver) are thread-safe and avoid check-then-act race conditions.

Hints

Hint 1

Watch out for default mutable arguments in Python function signatures like `drivers=[]`.

Hint 2

Consider what happens when two concurrent threads invoke `assign_driver` at the exact same moment on the same available driver.

Hint 3

Ensure value objects are immutable (e.g., `frozen=True` dataclasses) to prevent accidental external mutations.