The before code shows two services directly accessing the same shared database, causing tight coupling. The after code shows each service using its own database connection, enforcing database decomposition. Services communicate via events or APIs instead of shared tables.
### Before: Monolithic database access (violating decomposition)
class OrderService:
def create_order(self, user_id, product_id):
# Directly access shared orders table
db.execute("INSERT INTO orders (user_id, product_id) VALUES (?, ?)", (user_id, product_id))
class PaymentService:
def process_payment(self, order_id, amount):
# Directly access shared payments table
db.execute("INSERT INTO payments (order_id, amount) VALUES (?, ?)", (order_id, amount))
### After: Each service owns its own database
class OrderService:
def __init__(self, order_db):
self.order_db = order_db
def create_order(self, user_id, product_id):
self.order_db.execute("INSERT INTO orders (user_id, product_id) VALUES (?, ?)", (user_id, product_id))
class PaymentService:
def __init__(self, payment_db):
self.payment_db = payment_db
def process_payment(self, order_id, amount):
self.payment_db.execute("INSERT INTO payments (order_id, amount) VALUES (?, ?)", (order_id, amount))
# Communication via API or events instead of shared DB
# For example, OrderService emits event 'OrderCreated' that PaymentService listens to.