KatInterview

Complete Concrete Classes in an Abstract Base Hierarchy

Data Structure DesignModel answer
MediumModel answerData Structure Designobject-oriented-designinheritanceabstraction

Last updated

Implement missing methods in concrete subclasses that inherit from abstract base classes while maintaining type safety and LSP compliance.

You're working with a Python codebase that defines an abstract class hierarchy using abc.ABC and @abstractmethod. The abstract base classes and their public interfaces are already defined and cannot be changed. Your task is to complete the concrete subclass implementations marked with TODO or NotImplementedError.

The codebase represents a data processing pipeline with three stages: parsing raw input, validating structured data, and executing operations. Each stage is defined by an abstract base class, and you must implement the concrete versions.

Requirements:

  1. Preserve contracts: Do not modify any abstract base class, method signature, or public interface. Only implement the missing logic in concrete classes.

  2. Follow LSP: Your concrete classes must be substitutable for their base types. Any code expecting a Parser should work correctly with your CsvOrderParser.

  3. Respect error contracts: Docstrings specify which exception types each method should raise. Your implementation must raise exactly those types (translate internal exceptions where needed).

  4. Separate concerns: Each class should have a single responsibility. Use composition (dependency injection) rather than inheritance when you need external data or services.

  5. Handle edge cases: Account for malformed input, boundary conditions, and invalid data as indicated by type hints and docstrings.

  6. Write tests: Provide unit tests demonstrating that each class works correctly in isolation and that the pipeline integrates properly.

  7. Explain your approach: Briefly describe how you navigated the codebase to identify what needed implementation and avoided confusion in a ~200-line skeleton.

Given skeleton (you may not modify this):

from abc import ABC, abstractmethod
from dataclasses import dataclass
from decimal import Decimal
from typing import Mapping, Optional, Tuple

class PipelineError(Exception): pass
class ParseError(PipelineError): pass
class ValidationError(PipelineError): pass
class ExecutionError(PipelineError): pass

@dataclass(frozen=True)
class Order:
    symbol: str
    side: str        # "BUY" or "SELL"
    qty: int
    limit: Decimal

@dataclass(frozen=True)
class Fill:
    order: Order
    price: Decimal

class Parser(ABC):
    @abstractmethod
    def parse(self, raw: str) -> Order:
        """Parse 'SYMBOL,SIDE,QTY,LIMIT'. Raise ParseError on malformed input."""

class Validator(ABC):
    @abstractmethod
    def validate(self, order: Order) -> None:
        """Return None if valid; raise ValidationError on rule violation."""

class Executor(ABC):
    @abstractmethod
    def execute(self, order: Order) -> Optional[Fill]:
        """Return Fill if executable, else None. Raise ExecutionError for unknown symbols."""

class OrderPipeline:
    def __init__(self, parser: Parser, validator: Validator, executor: Executor):
        self._parser = parser
        self._validator = validator
        self._executor = executor

    def process(self, raw: str) -> Optional[Fill]:
        order = self._parser.parse(raw)
        self._validator.validate(order)
        return self._executor.execute(order)

Your task:

Implement CsvOrderParser(Parser), BasicOrderValidator(Validator), and QuoteBookExecutor(Executor) such that:

  • The parser handles CSV format with exactly 4 fields, converting types appropriately
  • The validator enforces business rules (valid side, positive quantity within limits, positive finite price)
  • The executor matches orders against a quote book (injected via constructor) and returns fills when the order is marketable

Provide test cases covering normal operation, edge cases, and error conditions.

Hints

Hint 1

Start by mapping every @abstractmethod to its concrete implementation site and reading the docstring contract before writing any code.

Hint 2

Read the orchestrator (OrderPipeline.process) first to understand the execution flow and what each stage expects from the previous one.

Hint 3

Translate internal exceptions (ValueError, KeyError, InvalidOperation) into the documented exception types using 'raise ... from' to preserve context.