Imperative programming describes computation as a sequence of commands that change program state. Functions in this style group statements, organize repeated logic, and drive objects or application data toward a desired outcome. section 1.3
Its central model makes both state changes and their control flow explicit: loops iterate, conditionals branch, assignments update variables, and data moves through those structures. This makes the algorithm’s operational steps visible, but nested branches and mutable counters can form a difficult-to-parse “pyramid of doom.” section 4.2 section 4.7
Imperative and functional approaches can express the same computation while emphasizing different concerns:
- Imperative code describes how to traverse data, maintain a running value, and decide which update occurs at each step. section 4.7
- Functional code emphasizes what transformations compose: filtering records, mapping transactions to values, reducing them immutably, and rounding the result. section 4.2 section 4.7
- The contrast is architectural rather than computational: both versions calculate the same result, but one exposes commands and state transitions while the other presents a data pipeline. section 4.2
Computing a wallet balance
A wallet can calculate its balance by iterating through a blockchain ledger, skipping the genesis block, visiting each transaction, subtracting outgoing funds, adding incoming funds, and rounding the final total. The imperative version keeps a mutable balance and updates it inside nested loops and conditionals. section 4.7
Listing 4.14 Imperative algorithm for computing total balance
balance(ledger) {
let balance = Money.zero();
for (const block of ledger) { #1
if (!block.isGenesis()) {
for (const tx of block.data) {
if (tx.sender === this.address) {
balance = balance.minus(tx.funds); #2
}
else {
balance = balance.plus(tx.funds); #2
}
}
}
}
return balance.round();
}
Inspect the imperative balance algorithm as a compact example of explicit iteration, branching, object state, and reassignment. section 4.7













