Complete Concrete Classes in an Abstract Base Hierarchy
Data Structure DesignModel answerLast 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:
-
Preserve contracts: Do not modify any abstract base class, method signature, or public interface. Only implement the missing logic in concrete classes.
-
Follow LSP: Your concrete classes must be substitutable for their base types. Any code expecting a
Parsershould work correctly with yourCsvOrderParser. -
Respect error contracts: Docstrings specify which exception types each method should raise. Your implementation must raise exactly those types (translate internal exceptions where needed).
-
Separate concerns: Each class should have a single responsibility. Use composition (dependency injection) rather than inheritance when you need external data or services.
-
Handle edge cases: Account for malformed input, boundary conditions, and invalid data as indicated by type hints and docstrings.
-
Write tests: Provide unit tests demonstrating that each class works correctly in isolation and that the pipeline integrates properly.
-
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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Before implementing anything, I build a mental map of the codebase:
-
Identify implementation points: Search for
@abstractmethod,TODO, andNotImplementedError. Create a checklist:Parser.parse→CsvOrderParser,Validator.validate→BasicOrderValidator,Executor.execute→QuoteBookExecutor. -
Understand the orchestrator: Read
OrderPipeline.processto see the execution flow. It calls parse → validate → execute in sequence, threading theOrderthrough each stage. This tells me the parser must produce a validOrderobject, the validator must check business rules without modifying it, and the executor must returnOptional[Fill]. -
Map exception contracts: Each docstring specifies what to raise. The parser raises
ParseErrorfor malformed input, the validator raisesValidationErrorfor rule violations, and the executor raisesExecutionErrorfor unknown symbols. Any internal exception (likeValueErrorfromint()orInvalidOperationfromDecimal()) must be caught and translated. -
Separate responsibilities: The parser handles syntax only (splitting strings, type conversion). The validator handles semantics (business rules on structured data). The executor handles matching logic (comparing orders against quotes). None should do another's job.
-
Implement leaves first: Each concrete class can be instantiated and tested independently. Python will raise
TypeErrorif abstract methods remain unimplemented, giving me a clear checklist.
Implementation
from decimal import InvalidOperation
class CsvOrderParser(Parser):
"""Handles syntax: splitting CSV and converting to typed Order."""
def parse(self, raw: str) -> Order:
if not isinstance(raw, str):
raise ParseError(f"Expected string input, got {type(raw).__name__}")
parts = [p.strip() for p in raw.split(",")]
if len(parts) != 4:
raise ParseError(f"Expected 4 comma-separated fields, found {len(parts)}")
symbol, side, qty_str, limit_str = parts
try:
qty = int(qty_str)
limit = Decimal(limit_str)
except (ValueError, InvalidOperation) as e:
raise ParseError(f"Cannot convert quantity or limit to number: {e}") from e
return Order(symbol.upper(), side.upper(), qty, limit)
class BasicOrderValidator(Validator):
"""Enforces business rules on structured Order objects."""
VALID_SIDES = frozenset({"BUY", "SELL"})
def __init__(self, max_qty: int = 1_000_000):
if max_qty <= 0:
raise ValueError("max_qty must be positive")
self._max_qty = max_qty
def validate(self, order: Order) -> None:
if not order.symbol or not order.symbol.replace("_", "").isalnum():
raise ValidationError(f"Invalid symbol: {order.symbol!r}")
if order.side not in self.VALID_SIDES:
raise ValidationError(f"Side must be BUY or SELL, got {order.side!r}")
if not (0 < order.qty <= self._max_qty):
raise ValidationError(
f"Quantity {order.qty} must be between 1 and {self._max_qty}"
)
if not order.limit.is_finite() or order.limit <= 0:
raise ValidationError(
f"Limit price must be positive and finite, got {order.limit}"
)
class QuoteBookExecutor(Executor):
"""Matches orders against bid/ask quotes from an injected source."""
def __init__(self, quotes: Mapping[str, Tuple[Decimal, Decimal]]):
# Defensive copy to prevent external mutation
self._quotes = dict(quotes)
def execute(self, order: Order) -> Optional[Fill]:
if order.symbol not in self._quotes:
raise ExecutionError(f"Unknown symbol: {order.symbol}")
bid, ask = self._quotes[order.symbol]
if order.side == "BUY":
# Buy orders match against the ask (offer) price
if order.limit >= ask:
return Fill(order, ask)
else: # SELL
# Sell orders match against the bid price
if order.limit <= bid:
return Fill(order, bid)
return None # Not marketable
Why This Works
Liskov Substitution Principle: Each subclass can be used wherever its base type is expected. Preconditions are not strengthened (the parser still accepts any string), postconditions are not weakened (each method returns the promised type or raises the documented exception), and invariants are preserved.
Exception Translation: Internal exceptions are caught and converted to the pipeline's error types. This prevents implementation details from leaking to callers. For example, Decimal("xyz") raises InvalidOperation, but we catch it and raise ParseError instead. Using raise ... from e preserves the original exception for debugging.
Single Responsibility: The parser doesn't validate quantity ranges. The validator doesn't parse strings. The executor doesn't check side validity. Each class does one thing, making them easier to test and maintain.
Composition over Inheritance: The executor receives its quote data via dependency injection rather than subclassing or hardcoding. This makes testing trivial (inject mock quotes) and allows swapping in a live data feed without modifying the class.
Edge Case Handling: The validator explicitly checks for non-finite decimals (Decimal("inf"), Decimal("NaN")) which would otherwise cause subtle bugs in the executor's price comparisons. The parser handles wrong field counts, empty strings, and non-numeric data.
Complexity
- Time: O(n) per order, where n is the length of the input string. Each stage does constant work except parsing (which scans the string). Quote lookup is O(1) average case.
- Space: O(n) for the parsed fields plus O(k) for the quote book, where k is the number of symbols.
Test Cases
import pytest
def test_parser_success():
parser = CsvOrderParser()
order = parser.parse("AAPL,BUY,100,150.50")
assert order == Order("AAPL", "BUY", 100, Decimal("150.50"))
def test_parser_wrong_field_count():
parser = CsvOrderParser()
with pytest.raises(ParseError, match="Expected 4"):
parser.parse("AAPL,BUY,100")
def test_parser_invalid_number():
parser = CsvOrderParser()
with pytest.raises(ParseError, match="Cannot convert"):
parser.parse("AAPL,BUY,abc,150.50")
def test_validator_success():
validator = BasicOrderValidator()
order = Order("AAPL", "BUY", 100, Decimal("150"))
validator.validate(order) # Should not raise
def test_validator_invalid_side():
validator = BasicOrderValidator()
order = Order("AAPL", "HOLD", 100, Decimal("150"))
with pytest.raises(ValidationError, match="Side must be"):
validator.validate(order)
def test_validator_infinite_price():
validator = BasicOrderValidator()
order = Order("AAPL", "BUY", 100, Decimal("inf"))
with pytest.raises(ValidationError, match="finite"):
validator.validate(order)
def test_executor_buy_marketable():
quotes = {"AAPL": (Decimal("149"), Decimal("151"))}
executor = QuoteBookExecutor(quotes)
order = Order("AAPL", "BUY", 100, Decimal("151"))
fill = executor.execute(order)
assert fill.price == Decimal("151")
def test_executor_buy_not_marketable():
quotes = {"AAPL": (Decimal("149"), Decimal("151"))}
executor = QuoteBookExecutor(quotes)
order = Order("AAPL", "BUY", 100, Decimal("150"))
assert executor.execute(order) is None
def test_executor_unknown_symbol():
executor = QuoteBookExecutor({})
order = Order("XXXX", "BUY", 100, Decimal("10"))
with pytest.raises(ExecutionError, match="Unknown symbol"):
executor.execute(order)
def test_pipeline_integration():
parser = CsvOrderParser()
validator = BasicOrderValidator()
quotes = {"AAPL": (Decimal("149.50"), Decimal("150.50"))}
executor = QuoteBookExecutor(quotes)
pipeline = OrderPipeline(parser, validator, executor)
fill = pipeline.process("AAPL,BUY,100,151.00")
assert fill is not None
assert fill.order.symbol == "AAPL"
assert fill.price == Decimal("150.50")
Common Mistakes
- Modifying the base classes: Changing method signatures or adding new abstract methods breaks the contract.
- Leaking internal exceptions: Letting
ValueErrororKeyErrorescape instead of translating to the documented exception types. - Mixing responsibilities: Having the parser validate business rules or the validator parse strings.
- Forgetting edge cases: Not checking for
Decimal("inf")orDecimal("NaN"), which parse successfully but break comparisons. - Hardcoding data: Putting quotes directly in the executor instead of injecting them, making testing harder.