ALD Python Example
A complete walkthrough: architect defines contracts, AI generates tests for approval, then AI generates implementation under SOLID constraints.
Step 1: Architect defines DTOs and interfaces
The architect identifies responsibilities: pricing calculation (a Strategy pattern) and order submission validation. These are roles, not layers.
contracts.py
Architect-defined contracts"""
Core domain contracts for order pricing and validation.
Framework-agnostic, immutable DTOs, role-based interfaces.
"""
from abc import ABC, abstractmethod
from dataclasses import dataclass
from decimal import Decimal
from enum import Enum
from typing import Optional
class CustomerSegment(Enum):
"""Customer tier classification."""
STANDARD = "standard"
PREMIUM = "premium"
ENTERPRISE = "enterprise"
@dataclass(frozen=True)
class OrderLineItem:
"""Represents a single line item in an order."""
product_id: str
quantity: int
unit_price: Decimal
def __post_init__(self):
if self.quantity <= 0:
raise ValueError("Quantity must be positive")
if self.unit_price < Decimal("0"):
raise ValueError("Unit price cannot be negative")
@dataclass(frozen=True)
class OrderDraft:
"""
An order before submission.
Immutable snapshot for validation and pricing.
"""
order_id: str
customer_id: str
customer_segment: CustomerSegment
line_items: tuple[OrderLineItem, ...]
promo_code: Optional[str] = None
def __post_init__(self):
if not self.line_items:
raise ValueError("Order must have at least one line item")
@dataclass(frozen=True)
class PricingResult:
"""Output of pricing calculation."""
subtotal: Decimal
discount: Decimal
tax: Decimal
total: Decimal
applied_promo: Optional[str] = None
@dataclass(frozen=True)
class ValidationResult:
"""Outcome of order validation."""
is_valid: bool
errors: tuple[str, ...] = ()
class OrderPricingStrategy(ABC):
"""
Role: Calculate order pricing based on business rules.
Pattern: Strategy
Responsibility: Price calculation (single responsibility)
"""
@abstractmethod
def calculate_price(self, order: OrderDraft) -> PricingResult:
"""
Calculate final pricing for an order draft.
Args:
order: The order to price
Returns:
Complete pricing breakdown
Raises:
ValueError: If order data is invalid for pricing
"""
pass
class OrderSubmissionValidator(ABC):
"""
Role: Validate order before submission.
Pattern: Strategy/Policy
Responsibility: Business rule validation (single responsibility)
"""
@abstractmethod
def validate(self, order: OrderDraft) -> ValidationResult:
"""
Validate order meets business rules for submission.
Args:
order: The order to validate
Returns:
Validation result with any error messages
"""
pass
frozen=True). Interfaces are focused (SRP/ISP).
Step 2: AI generates contract tests
Using the ALD prompt kit, the architect asks AI to generate tests that define behavioral expectations. The architect reviews and approves these tests before any implementation exists.
We are using ALD. I want you to define the behavioral contract.
Given these interfaces/DTOs (do not change them):
[contracts.py from above]
Write only unit tests (no implementation) that encode:
- happy paths
- edge cases
- invalid inputs and error behavior
- invariants and ordering constraints (if any)
test_contracts.py
AI-generated, architect-approved"""
Contract tests for OrderPricingStrategy and OrderSubmissionValidator.
These define expected behavior before implementation exists.
"""
import pytest
from decimal import Decimal
from contracts import (
OrderDraft, OrderLineItem, CustomerSegment,
PricingResult, ValidationResult,
OrderPricingStrategy, OrderSubmissionValidator
)
class TestOrderPricingStrategyContract:
"""
Contract tests for any OrderPricingStrategy implementation.
Tests behavior, not implementation details.
"""
def test_calculates_subtotal_from_line_items(self, pricing_strategy: OrderPricingStrategy):
"""Happy path: basic subtotal calculation."""
order = OrderDraft(
order_id="ORD-001",
customer_id="CUST-001",
customer_segment=CustomerSegment.STANDARD,
line_items=(
OrderLineItem("PROD-A", quantity=2, unit_price=Decimal("10.00")),
OrderLineItem("PROD-B", quantity=1, unit_price=Decimal("5.50")),
)
)
result = pricing_strategy.calculate_price(order)
assert result.subtotal == Decimal("25.50")
assert result.total >= result.subtotal # total includes tax
def test_applies_discount_for_premium_customers(self, pricing_strategy: OrderPricingStrategy):
"""Premium customers should receive discounts."""
order = OrderDraft(
order_id="ORD-002",
customer_id="CUST-002",
customer_segment=CustomerSegment.PREMIUM,
line_items=(
OrderLineItem("PROD-A", quantity=1, unit_price=Decimal("100.00")),
)
)
result = pricing_strategy.calculate_price(order)
assert result.discount > Decimal("0")
assert result.total < result.subtotal # discount reduces total
def test_applies_promo_code_discount(self, pricing_strategy: OrderPricingStrategy):
"""Promo codes should be applied and tracked."""
order = OrderDraft(
order_id="ORD-003",
customer_id="CUST-003",
customer_segment=CustomerSegment.STANDARD,
line_items=(
OrderLineItem("PROD-A", quantity=1, unit_price=Decimal("50.00")),
),
promo_code="SAVE10"
)
result = pricing_strategy.calculate_price(order)
assert result.applied_promo == "SAVE10"
assert result.discount > Decimal("0")
def test_ignores_invalid_promo_code(self, pricing_strategy: OrderPricingStrategy):
"""Invalid promo codes should be ignored, not error."""
order = OrderDraft(
order_id="ORD-004",
customer_id="CUST-004",
customer_segment=CustomerSegment.STANDARD,
line_items=(
OrderLineItem("PROD-A", quantity=1, unit_price=Decimal("50.00")),
),
promo_code="INVALID"
)
result = pricing_strategy.calculate_price(order)
assert result.applied_promo is None
assert result.discount == Decimal("0")
def test_includes_tax_in_total(self, pricing_strategy: OrderPricingStrategy):
"""Tax should be calculated and included in total."""
order = OrderDraft(
order_id="ORD-005",
customer_id="CUST-005",
customer_segment=CustomerSegment.STANDARD,
line_items=(
OrderLineItem("PROD-A", quantity=1, unit_price=Decimal("100.00")),
)
)
result = pricing_strategy.calculate_price(order)
assert result.tax > Decimal("0")
assert result.total == result.subtotal - result.discount + result.tax
class TestOrderSubmissionValidatorContract:
"""
Contract tests for any OrderSubmissionValidator implementation.
"""
def test_valid_order_passes(self, submission_validator: OrderSubmissionValidator):
"""Happy path: valid order."""
order = OrderDraft(
order_id="ORD-100",
customer_id="CUST-100",
customer_segment=CustomerSegment.STANDARD,
line_items=(
OrderLineItem("PROD-A", quantity=1, unit_price=Decimal("10.00")),
)
)
result = submission_validator.validate(order)
assert result.is_valid is True
assert len(result.errors) == 0
def test_rejects_excessive_quantity(self, submission_validator: OrderSubmissionValidator):
"""Edge case: quantity exceeds business limit."""
order = OrderDraft(
order_id="ORD-101",
customer_id="CUST-101",
customer_segment=CustomerSegment.STANDARD,
line_items=(
OrderLineItem("PROD-A", quantity=10000, unit_price=Decimal("1.00")),
)
)
result = submission_validator.validate(order)
assert result.is_valid is False
assert any("quantity" in err.lower() for err in result.errors)
def test_rejects_excessive_order_total(self, submission_validator: OrderSubmissionValidator):
"""Business rule: orders over $50k require special approval."""
order = OrderDraft(
order_id="ORD-102",
customer_id="CUST-102",
customer_segment=CustomerSegment.STANDARD,
line_items=(
OrderLineItem("PROD-A", quantity=1, unit_price=Decimal("60000.00")),
)
)
result = submission_validator.validate(order)
assert result.is_valid is False
assert any("total" in err.lower() or "limit" in err.lower() for err in result.errors)
def test_accepts_high_value_for_enterprise(self, submission_validator: OrderSubmissionValidator):
"""Enterprise customers have higher limits."""
order = OrderDraft(
order_id="ORD-103",
customer_id="CUST-103",
customer_segment=CustomerSegment.ENTERPRISE,
line_items=(
OrderLineItem("PROD-A", quantity=1, unit_price=Decimal("60000.00")),
)
)
result = submission_validator.validate(order)
# Enterprise should have higher or no limit
# (exact behavior depends on business rules)
assert result.is_valid is True or "enterprise" not in str(result.errors).lower()
# Fixtures would be injected by pytest
@pytest.fixture
def pricing_strategy() -> OrderPricingStrategy:
"""Fixture to inject concrete implementation (to be created)."""
# This will be implemented after tests are approved
from implementations import StandardPricingStrategy
return StandardPricingStrategy()
@pytest.fixture
def submission_validator() -> OrderSubmissionValidator:
"""Fixture to inject concrete implementation (to be created)."""
# This will be implemented after tests are approved
from implementations import StandardSubmissionValidator
return StandardSubmissionValidator()
Step 3: AI generates implementations
With approved tests in place, the architect uses the ALD implementation prompt. AI generates concrete classes that satisfy the contracts.
You are implementing Architect-Led Development (ALD).
Given the following interfaces and DTOs (DO NOT change signatures):
[contracts.py]
And these approved contract tests:
[test_contracts.py]
Task:
1) Implement concrete classes for these interfaces.
2) Make sure all tests pass.
3) Keep dependencies injectable. No global state.
4) Follow SOLID principles.
Output: implementation code only.
implementations.py
AI-generated implementation"""
Concrete implementations of pricing and validation contracts.
Strategy pattern: different pricing strategies can be swapped.
"""
from decimal import Decimal
from typing import Optional
from contracts import (
OrderDraft, OrderLineItem, CustomerSegment,
PricingResult, ValidationResult,
OrderPricingStrategy, OrderSubmissionValidator
)
class StandardPricingStrategy(OrderPricingStrategy):
"""
Standard pricing implementation with segment-based discounts.
Business rules:
- Standard customers: no discount
- Premium customers: 10% discount
- Enterprise customers: 15% discount
- Promo codes: additional fixed discount
- Tax rate: 8%
"""
# Configuration (could be injected via constructor for flexibility)
SEGMENT_DISCOUNTS = {
CustomerSegment.STANDARD: Decimal("0"),
CustomerSegment.PREMIUM: Decimal("0.10"),
CustomerSegment.ENTERPRISE: Decimal("0.15"),
}
PROMO_CODES = {
"SAVE10": Decimal("10.00"),
"SAVE20": Decimal("20.00"),
"WELCOME": Decimal("5.00"),
}
TAX_RATE = Decimal("0.08")
def calculate_price(self, order: OrderDraft) -> PricingResult:
"""Calculate pricing with discounts and tax."""
# Calculate subtotal
subtotal = sum(
item.unit_price * item.quantity
for item in order.line_items
)
# Apply segment discount
segment_discount_rate = self.SEGMENT_DISCOUNTS[order.customer_segment]
segment_discount = subtotal * segment_discount_rate
# Apply promo code discount
promo_discount = Decimal("0")
applied_promo: Optional[str] = None
if order.promo_code and order.promo_code in self.PROMO_CODES:
promo_discount = self.PROMO_CODES[order.promo_code]
applied_promo = order.promo_code
total_discount = segment_discount + promo_discount
# Calculate tax on discounted amount
taxable_amount = subtotal - total_discount
tax = taxable_amount * self.TAX_RATE
# Calculate final total
total = subtotal - total_discount + tax
return PricingResult(
subtotal=subtotal,
discount=total_discount,
tax=tax,
total=total,
applied_promo=applied_promo
)
class StandardSubmissionValidator(OrderSubmissionValidator):
"""
Validates orders against business rules before submission.
Business rules:
- Max quantity per line item: 1000 (standard/premium), 10000 (enterprise)
- Max order total: $50,000 (standard/premium), unlimited (enterprise)
- Must have at least one line item (enforced by DTO)
"""
MAX_QUANTITY_STANDARD = 1000
MAX_QUANTITY_ENTERPRISE = 10000
MAX_ORDER_TOTAL_STANDARD = Decimal("50000.00")
def validate(self, order: OrderDraft) -> ValidationResult:
"""Validate order against business rules."""
errors = []
# Check quantity limits
max_quantity = (
self.MAX_QUANTITY_ENTERPRISE
if order.customer_segment == CustomerSegment.ENTERPRISE
else self.MAX_QUANTITY_STANDARD
)
for item in order.line_items:
if item.quantity > max_quantity:
errors.append(
f"Line item {item.product_id} exceeds maximum quantity "
f"of {max_quantity}"
)
# Check order total limits (only for non-enterprise)
if order.customer_segment != CustomerSegment.ENTERPRISE:
order_subtotal = sum(
item.unit_price * item.quantity
for item in order.line_items
)
if order_subtotal > self.MAX_ORDER_TOTAL_STANDARD:
errors.append(
f"Order total ${order_subtotal} exceeds limit of "
f"${self.MAX_ORDER_TOTAL_STANDARD} for {order.customer_segment.value} customers"
)
return ValidationResult(
is_valid=len(errors) == 0,
errors=tuple(errors)
)
pytest test_contracts.py to verify.
Implementation is complete and contract-compliant.
Step 4: Refactor and extend (manually or via AI)
Now the architect can refactor implementations or add new strategies—without touching the contracts or tests. This can be done manually or by prompting AI with extension requirements.
Example: Adding a holiday pricing strategy using the Decorator pattern to wrap existing pricing logic.
ALD extension request.
Current implementation:
[StandardPricingStrategy from implementations.py]
Requirement:
Add a HolidayPricingStrategy that wraps any existing pricing strategy and applies an additional percentage discount.
Constraints:
- Use Decorator pattern (composition, not inheritance)
- Do NOT modify existing contracts or implementations
- Must satisfy OrderPricingStrategy interface
- Keep it testable and injectable
Deliver: New class implementation with usage example.
implementations.py (extended)
New strategy added via compositionclass HolidayPricingStrategy(OrderPricingStrategy):
"""
Holiday pricing: delegates to standard pricing, then applies additional discount.
Pattern: Decorator (wraps another strategy)
"""
def __init__(self, base_strategy: OrderPricingStrategy, holiday_discount: Decimal):
self._base = base_strategy
self._holiday_discount = holiday_discount
def calculate_price(self, order: OrderDraft) -> PricingResult:
"""Apply base pricing, then add holiday discount."""
base_result = self._base.calculate_price(order)
additional_discount = base_result.subtotal * self._holiday_discount
new_discount = base_result.discount + additional_discount
new_total = base_result.subtotal - new_discount + base_result.tax
return PricingResult(
subtotal=base_result.subtotal,
discount=new_discount,
tax=base_result.tax,
total=new_total,
applied_promo=base_result.applied_promo
)
# Usage: compose strategies at runtime
standard_pricing = StandardPricingStrategy()
holiday_pricing = HolidayPricingStrategy(
base_strategy=standard_pricing,
holiday_discount=Decimal("0.05") # 5% holiday discount
)
Architect's choice: Write extensions manually when you want precise control, or delegate to AI when the pattern is clear and the requirements are well-defined.
Step 5: Integration (framework adapter)
Core logic stays framework-agnostic. Integration with FastAPI/Flask/Django happens at the edges via adapters.
api.py
FastAPI adapter (thin boundary layer)"""
FastAPI adapter layer.
Maps HTTP requests to domain contracts.
"""
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from decimal import Decimal
from typing import Optional
from contracts import (
OrderDraft, OrderLineItem, CustomerSegment,
OrderPricingStrategy, OrderSubmissionValidator
)
from implementations import StandardPricingStrategy, StandardSubmissionValidator
# Pydantic models for HTTP (separate from domain DTOs)
class LineItemRequest(BaseModel):
product_id: str
quantity: int
unit_price: Decimal
class OrderRequest(BaseModel):
order_id: str
customer_id: str
customer_segment: str
line_items: list[LineItemRequest]
promo_code: Optional[str] = None
class PriceResponse(BaseModel):
subtotal: Decimal
discount: Decimal
tax: Decimal
total: Decimal
applied_promo: Optional[str] = None
# Dependency injection (could use FastAPI's Depends)
pricing_strategy: OrderPricingStrategy = StandardPricingStrategy()
validator: OrderSubmissionValidator = StandardSubmissionValidator()
app = FastAPI()
@app.post("/orders/calculate-price", response_model=PriceResponse)
def calculate_order_price(request: OrderRequest):
"""
Calculate pricing for an order.
Adapter: HTTP request → domain contract → HTTP response
"""
# Map HTTP request to domain DTO
try:
order = OrderDraft(
order_id=request.order_id,
customer_id=request.customer_id,
customer_segment=CustomerSegment(request.customer_segment),
line_items=tuple(
OrderLineItem(
product_id=item.product_id,
quantity=item.quantity,
unit_price=item.unit_price
)
for item in request.line_items
),
promo_code=request.promo_code
)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
# Execute domain logic
result = pricing_strategy.calculate_price(order)
# Map domain result to HTTP response
return PriceResponse(
subtotal=result.subtotal,
discount=result.discount,
tax=result.tax,
total=result.total,
applied_promo=result.applied_promo
)
@app.post("/orders/validate")
def validate_order(request: OrderRequest):
"""Validate order before submission."""
try:
order = OrderDraft(
order_id=request.order_id,
customer_id=request.customer_id,
customer_segment=CustomerSegment(request.customer_segment),
line_items=tuple(
OrderLineItem(
product_id=item.product_id,
quantity=item.quantity,
unit_price=item.unit_price
)
for item in request.line_items
),
promo_code=request.promo_code
)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
result = validator.validate(order)
if not result.is_valid:
raise HTTPException(
status_code=422,
detail={"errors": list(result.errors)}
)
return {"status": "valid"}
Summary: ALD workflow in practice
What the architect owns
- Contract design (DTOs, interfaces)
- Responsibility boundaries (SRP/ISP)
- Test approval (behavior validation)
- Pattern selection and composition
- Architecture decisions
What AI generates
- Contract test scaffolding
- Concrete implementations
- Boilerplate code
- Edge case handling
- Framework adapters