Implementing DCI in Nim: A Practical Walkthrough

Implementing DCI in Nim requires no external libraries or AST macros. Three native features – distinct types, Uniform Function Call Syntax (UFCS), and module-level visibility – provide compile-time role safety with zero runtime cost.

1. Data: Pure Domain State

The Data layer defines the Account entity and enforces basic state integrity. It carries no knowledge of transfers or roles.

account.nim
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 -= amount

The * export marker exposes Account and its primitive balance operations to the rest of the application.

2. Context, Roles, and Interactions

The Context module defines the roles (SourceAccount and DestinationAccount) as distinct Account types. In Nim, a distinct type creates a brand-new type at compile time that shares the underlying memory representation of Account without inheriting its procedures automatically.

money_transfer.nim
import account
# Roles: zero-cost compile-time wrappers around Account
type
SourceAccount = distinct Account
DestinationAccount = distinct Account
# Explicit conversion helper scoped privately to this Context
template data(role: SourceAccount | DestinationAccount): Account =
Account(role)
# Interactions: role methods visible only inside this module
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) =
self.withdraw(amount)
dest.deposit(amount)
# Context: binds Data to Roles and executes the use case
type
MoneyTransferContext* = object
source: SourceAccount
destination: DestinationAccount
amount: int
proc initMoneyTransfer*(fromAcc, toAcc: Account, amount: int): MoneyTransferContext =
MoneyTransferContext(
source: SourceAccount(fromAcc),
destination: DestinationAccount(toAcc),
amount: amount
)
proc execute*(ctx: MoneyTransferContext) =
ctx.source.transferTo(ctx.destination, ctx.amount)

Three properties make this structure robust:

3. Running the Use Case

The application entry point creates plain Account records and passes them into MoneyTransferContext.

main.nim
import account, money_transfer
let checking = Account(id: "CHK-01", balance: 1000)
let savings = Account(id: "SAV-01", balance: 250)
let transfer = initMoneyTransfer(fromAcc = checking, toAcc = savings, amount = 300)
transfer.execute()
echo "Checking: ", checking.balance # 700
echo "Savings: ", savings.balance # 550