Implementing DCI in Nim: Zero-Overhead Roles with Distinct Types
A step-by-step tutorial building the classic DCI Money Transfer use case in Nim using distinct types, UFCS, and module scoping.
In Part 2, we looked at how Data, Context, and Interaction (DCI) separates stable domain state (Data) from use-case workflows (Roles and Interactions).
Now let’s build the classic DCI Money Transfer example in idiomatic Nim. Instead of runtime mixins or wrapper allocations, we will use three built-in Nim features:
distincttypes for zero-cost, compile-time Role safety.- Uniform Function Call Syntax (UFCS) for readable Role interactions.
- Module-level visibility so Role methods exist only inside their Context.
Step 1: The Data Layer
First, we define our domain object. In DCI, Data objects represent what the system is. Our Account holds its state and exposes primitive operations to mutate its own balance, but it has no concept of transfers, source accounts, or destination accounts.
type Account* = ref object id*: string balance*: int
proc increaseBalance*(self: Account, amount: int) = self.balance += amount
proc decreaseBalance*(self: Account, amount: int) = if self.balance < amount: raise newException(ValueError, "Insufficient funds") self.balance -= amountNotice that Account is completely decoupled from any business workflow. You can reuse it across dozens of use cases without ever bloating this file.
Step 2: Roles, Interactions, and Context
Next, we create a dedicated module for a single use case: transferring money between two accounts.
Here is how each piece of DCI maps into money_transfer.nim:
- Roles (
distinct Account): By declaringSourceAccountandDestinationAccountasdistincttypes, we tell the Nim compiler to treat them as completely separate types during type checking – even though they compile down to the exact same pointer asAccountat runtime. - Interactions (Private
procs): Becausedeposit,withdraw, andtransferToomit the export marker (*), they are lexically scoped to this file. Outside this Context, anAccountcannot perform Role behaviors. - Context (
MoneyTransferContext): Binds the concreteAccountinstances to their Roles and triggers the interaction.
import account
# --- 1. ROLES ---# Zero-cost compile-time wrappers around Accounttype SourceAccount = distinct Account DestinationAccount = distinct Account
# Helper template to unwrap a Role back to its underlying Data objecttemplate data(role: SourceAccount | DestinationAccount): Account = Account(role)
# --- 2. INTERACTIONS (Role Methods) ---# Scoped privately to this module so they never pollute the Data model
proc deposit(self: DestinationAccount, amount: int) = self.data.increaseBalance(amount)
proc withdraw(self: SourceAccount, amount: int) = self.data.decreaseBalance(amount)
proc transferTo(self: SourceAccount, dest: DestinationAccount, amount: int) = # Reads just like the business requirement self.withdraw(amount) dest.deposit(amount)
# --- 3. CONTEXT ---type MoneyTransferContext* = object source: SourceAccount destination: DestinationAccount amount: int
proc initMoneyTransfer*(fromAcc, toAcc: Account, amount: int): MoneyTransferContext = # Role binding happens explicitly here MoneyTransferContext( source: SourceAccount(fromAcc), destination: DestinationAccount(toAcc), amount: amount )
proc execute*(ctx: MoneyTransferContext) = # Trigger the interaction ctx.source.transferTo(ctx.destination, ctx.amount)Why This Works So Well
Look closely at line 22 (proc transferTo). If you accidentally swap self and dest inside the Context, Nim refuses to compile because DestinationAccount does not have a withdraw proc. You get strict Role isolation with zero runtime wrapper allocations.
Step 3: Executing the Use Case
Finally, your application entry point creates plain Data objects and hands them off to the Context.
import account, money_transfer
let checking = Account(id: "CHK-01", balance: 1000)let savings = Account(id: "SAV-01", balance: 250)
# Instantiate the Context, bind Roles, and run the interactionlet transfer = initMoneyTransfer(fromAcc = checking, toAcc = savings, amount = 300)transfer.execute()
echo "Checking: ", checking.balance # 700echo "Savings: ", savings.balance # 550
# Compile-time safety check:# checking.transferTo(savings, 100) -> Error: undeclared field: 'transferTo'Up Next
Our SourceAccount Role currently only works with a concrete Account type. In Part 4, we will use Nim concepts so completely unrelated Data types – like a CheckingAccount and a CreditCard – can play the exact same Role, and compare Nim’s static approach to dynamic languages like Perl.
