The before code updates the account balance directly, losing history. The after code records each change as an event in an event store and rebuilds the balance by replaying these events, preserving full history.
### Before: naive state update without event sourcing
class Account:
def __init__(self):
self.balance = 0
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
self.balance -= amount
### After: event sourcing with event log
class EventStore:
def __init__(self):
self.events = []
def append(self, event):
self.events.append(event)
def get_events(self):
return self.events
class Account:
def __init__(self, event_store):
self.balance = 0
self.event_store = event_store
self.replay_events()
def replay_events(self):
for event in self.event_store.get_events():
self.apply(event)
def apply(self, event):
if event['type'] == 'deposit':
self.balance += event['amount']
elif event['type'] == 'withdraw':
self.balance -= event['amount']
def deposit(self, amount):
event = {'type': 'deposit', 'amount': amount}
self.event_store.append(event)
self.apply(event)
def withdraw(self, amount):
event = {'type': 'withdraw', 'amount': amount}
self.event_store.append(event)
self.apply(event)