Implement Apply and Load for an event-sourced bank account
An Account aggregate is rebuilt from its events. Implement Apply, which updates the state for one event, and Load, which builds an account from its history.
Requirements: Apply must not return an error, call anything external or check business rules — events are facts that already happened. Unknown event types change nothing. Load applies the events in the given order and sets Version to the number of events in the history.
type Event interface{ isEvent() }
type Opened struct{ ID, Owner string }
type Deposited struct{ Amount int64 }
type Withdrawn struct{ Amount int64 }
func (Opened) isEvent() {}
func (Deposited) isEvent() {}
func (Withdrawn) isEvent() {}
type Account struct {
ID string
Owner string
Balance int64
Open bool
Version int
}
func (a *Account) Apply(e Event) {
// your code here
}
func Load(history []Event) *Account {
// your code here
}Write the implementation.
Apply uses a type switch and only mutates state: Opened sets the id, owner and open flag, Deposited adds, Withdrawn subtracts, anything else is ignored. Load starts from a zero Account, applies the history in order and counts it into Version.
- Checking business rules inside
Applyand skipping events that break them - Calling external services or
time.Now()fromApply, making replay non-deterministic - Re-running commands during load instead of applying the recorded events
- Where would the insufficient-funds check live if not in
Apply? - How would you collect the new events a command produces before saving them?
Solution
func (a *Account) Apply(e Event) {
switch e := e.(type) {
case Opened:
a.ID, a.Owner, a.Open = e.ID, e.Owner, true
case Deposited:
a.Balance += e.Amount
case Withdrawn:
a.Balance -= e.Amount // no check: the withdrawal already happened
}
// unknown type — change nothing
}
func Load(history []Event) *Account {
a := &Account{}
for _, e := range history {
a.Apply(e)
a.Version++ // the version counts every stream event, even an unknown one
}
return a
}Why no checks. A Withdrawn event is already recorded — so Handle made the decision, checking the balance before the write. If Apply refuses to apply a fact, the stream becomes unloadable, and skipping the event silently yields a state that never existed in history. The "are there enough funds" check lives in the command handler, not here.
Why the version is counted in Load. The version is the number of the stream's last event, and the next write passes it as the expected version. If unknown events were skipped in the count, the version would drift from the store and every write would fail with a conflict.
Determinism. Apply has no time.Now(), no network calls, and no randomness: the same history must yield the same state on every load, every rebuild, and in tests.