The before code updates the account balance directly, losing history. The after code appends each change as an event to the event store and applies it, preserving full change history and enabling state reconstruction.
### Before: naive state update without event store
class Account:
def __init__(self):
self.balance = 0
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
self.balance -= amount
### After: event store records all changes as events
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)