Give examples of Domain-Driven Design examples in python.
Assistant
Domain-Driven Design (DDD) Examples in Python
Domain-Driven Design focuses on modeling business domains using rich domain models, clear boundaries, and ubiquitous language. Here are comprehensive Python examples:
1. Core DDD Building Blocks
Value Objects (Immutable)
python
from dataclasses import dataclass
from typing import Self
from decimal import Decimal
@dataclass(frozen=True) # Immutable
class Money:
amount: Decimal
currency: str = "USD"
def __post_init__(self):
if self.amount < 0:
raise ValueError("Money amount cannot be negative")
if len(self.currency) != 3:
raise ValueError("Currency must be 3-letter code")
def add(self, other: Self) -> Self:
if self.currency != other.currency:
raise ValueError("Cannot add different currencies")
return Money(self.amount + other.amount, self.currency)
def subtract(self, other: Self) -> Self:
if self.currency != other.currency:
raise ValueError("Cannot subtract different currencies")
return Money(self.amount - other.amount, self.currency)
def __str__(self) -> str:
return f"{self.currency} {self.amount:.2f}"
# Usage
price = Money(Decimal("29.99"))
discount = Money(Decimal("5.00"))
final_price = price.subtract(discount)
print(final_price) # USD 24.99
Entities (Mutable with Identity)
python
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
class OrderService:
def __init__(self,
order_repository: Repository[Order, uuid.UUID],
product_repository: ProductRepository,
pricing_service: PricingService):
self.order_repository = order_repository
self.product_repository = product_repository
self.pricing_service = pricing_service
def create_order(self, customer_id: uuid.UUID) -> Order:
"""Create a new draft order."""
order = Order(customer_id=customer_id)
return self.order_repository.save(order)
def add_item_to_order(self,
order_id: uuid.UUID,
product_id: ProductId,
quantity: int) -> Order:
"""Add item to an existing order."""
order = self.order_repository.get_by_id(order_id)
if not order:
raise OrderNotFoundError(f"Order {order_id} not found")
product = self.product_repository.get_by_id(product_id)
if not product:
raise ProductNotFoundError(f"Product {product_id} not found")
# Use pricing service to get current price
unit_price = self.pricing_service.calculate_final_price(
product, quantity, {"customer_id": order.customer_id}
)
order.add_item(product_id, quantity, unit_price)
return self.order_repository.save(order)
def confirm_order(self, order_id: uuid.UUID) -> Order:
"""Confirm an order for processing."""
order = self.order_repository.get_by_id(order_id)
if not order:
raise OrderNotFoundError(f"Order {order_id} not found")
order.confirm()
# Domain event could be raised here
# self.event_publisher.publish(OrderConfirmedEvent(order_id))
return self.order_repository.save(order)
class OrderNotFoundError(Exception):
pass
class ProductNotFoundError(Exception):
pass
6. Domain Events
Event System for Domain Changes
python
from dataclasses import dataclass
from datetime import datetime
from typing import Any, Dict
import uuid
@dataclass
class DomainEvent:
event_id: uuid.UUID = field(default_factory=uuid.uuid4)
occurred_on: datetime = field(default_factory=datetime.now)
version: int = 1
@dataclass
class OrderConfirmedEvent(DomainEvent):
order_id: uuid.UUID
customer_id: uuid.UUID
total_amount: Money
class EventPublisher:
def __init__(self):
self.subscribers: Dict[type, List[callable]] = {}
def subscribe(self, event_type: type, handler: callable):
if event_type not in self.subscribers:
self.subscribers[event_type] = []
self.subscribers[event_type].append(handler)
def publish(self, event: DomainEvent):
event_type = type(event)
if event_type in self.subscribers:
for handler in self.subscribers[event_type]:
handler(event)
# Domain event handler
class OrderConfirmedHandler:
def __init__(self, email_service, inventory_service):
self.email_service = email_service
self.inventory_service = inventory_service
def handle(self, event: OrderConfirmedEvent):
# Send confirmation email
self.email_service.send_order_confirmation(event.order_id)
# Reserve inventory
self.inventory_service.reserve_items_for_order(event.order_id)
# Usage in aggregate
@dataclass
class Order:
# ... previous code ...
def confirm(self) -> None:
if not self.items:
raise InvalidOperationError("Cannot confirm empty order")
if self.status != OrderStatus.DRAFT:
raise InvalidOperationError("Order already confirmed")
self.status = OrderStatus.CONFIRMED
self._version += 1
# Raise domain event
self.events.append(OrderConfirmedEvent(
order_id=self.order_id,
customer_id=self.customer_id,
total_amount=self.total_amount
))
7. Bounded Contexts
Separate Contexts for Different Subdomains
python
# Sales Bounded Context
@dataclass
class SalesOrder:
order_id: uuid.UUID
customer_id: uuid.UUID
items: List[OrderItem]
status: OrderStatus
# Shipping Bounded Context (Different model for same concept)
@dataclass
class Shipment:
shipment_id: uuid.UUID
order_id: uuid.UUID # Reference to sales context
packages: List[Package]
carrier: str
tracking_number: str
status: ShipmentStatus
# Anti-Corruption Layer between contexts
class ShippingAdapter:
def __init__(self, sales_order_repository):
self.sales_order_repository = sales_order_repository
def create_shipment_from_order(self, order_id: uuid.UUID) -> Shipment:
sales_order = self.sales_order_repository.get_by_id(order_id)
# Translate between bounded contexts
packages = self._create_packages_from_order_items(sales_order.items)
return Shipment(
shipment_id=uuid.uuid4(),
order_id=order_id,
packages=packages,
carrier="UPS",
tracking_number=self._generate_tracking_number(),
status=ShipmentStatus.PENDING
)
def _create_packages_from_order_items(self, items: List[OrderItem]) -> List[Package]:
# Complex domain logic for packaging
pass
8. Factory Pattern for Complex Object Creation
python
class OrderFactory:
@staticmethod
def create_order_with_items(customer_id: uuid.UUID,
items_data: List[dict],
product_repository: ProductRepository) -> Order:
"""Factory method for creating orders with initial items."""
order = Order(customer_id=customer_id)
for item_data in items_data:
product_id = ProductId(uuid.UUID(item_data['product_id']))
product = product_repository.get_by_id(product_id)
if not product:
raise ProductNotFoundError(f"Product {product_id} not found")
order.add_item(product_id, item_data['quantity'], product.price)
return order
# Usage
factory = OrderFactory()
order = factory.create_order_with_items(
customer_id=uuid.uuid4(),
items_data=[{"product_id": str(product.product_id.value), "quantity": 2}],
product_repository=product_repo
)
Key DDD Principles Demonstrated
Ubiquitous Language: Class and method names reflect business terms
Aggregates: Order manages its items and enforces invariants
Value Objects: Money is immutable and has business logic
Domain Services: Stateless business logic (PricingService)
Repositories: Abstract data access
Domain Events: Communicate changes between aggregates
Bounded Contexts: Separate models for different business capabilities
These patterns make the code business-focused, testable, and maintainable while accurately modeling complex domain logic.