DCI in Nim Deeper Dive: Polymorphic Roles, Trade-offs, and Dynamic Comparisons

Scaling DCI in Nim using structural concepts, deciding when not to write a macro DSL, and comparing compile-time Roles with runtime Perl injection.

In Part 3, we built a working DCI Money Transfer in Nim where SourceAccount and DestinationAccount were distinct wrappers around a single Account type.

In real applications, however, Roles rarely bind to just one concrete type. What if a user wants to transfer money from a CheckingAccount to a SavingsAccount – or pay off a CreditCard?

In this final part of the series, we will make our Roles polymorphic using Nim Concepts, evaluate whether a custom macro DSL is worth building, and compare Nim’s compile-time model with dynamic languages like Perl.

1. Polymorphic Roles with Nim concepts

Nim’s concept feature provides compile-time structural typing (similar to interfaces in Go or traits in Rust, but checked duck-typing at compile time). Instead of binding a Role to a specific object, we define the minimal contract a Data object must satisfy to play that Role.

Heterogeneous Data Types

Suppose we have two completely unrelated domain types with different internal fields:

accounts.nim
type
CheckingAccount* = ref object
accountNumber*: string
balance*: int
CreditCard* = ref object
cardNumber*: string
currentDebt*: int
creditLimit*: int
# CheckingAccount satisfies both withdrawing and depositing
proc withdrawFunds*(acc: CheckingAccount, amount: int) =
if acc.balance < amount:
raise newException(ValueError, "Insufficient checking balance")
acc.balance -= amount
proc depositFunds*(acc: CheckingAccount, amount: int) =
acc.balance += amount
# CreditCard only satisfies depositing (paying down debt)
proc depositFunds*(card: CreditCard, amount: int) =
card.currentDebt -= amount

Notice that CreditCard intentionally does not implement withdrawFunds.

Binding Concepts to Generic Contexts

Inside our Context, we define concept contracts for CanWithdraw and CanDeposit, then make MoneyTransferContext generic over those concepts:

polymorphic_transfer.nim
import accounts
# --- ROLE CONTRACTS (Concepts) ---
type
CanWithdraw = concept x
x.withdrawFunds(int)
CanDeposit = concept x
x.depositFunds(int)
# --- INTERACTIONS ---
# Any pair of types matching the Role contracts can interact
proc transferTo[S: CanWithdraw, D: CanDeposit](source: S, dest: D, amount: int) =
source.withdrawFunds(amount)
dest.depositFunds(amount)
# --- GENERIC CONTEXT ---
type
MoneyTransferContext*[S: CanWithdraw, D: CanDeposit] = object
source: S
destination: D
amount: int
proc initMoneyTransfer*[S: CanWithdraw, D: CanDeposit](
fromAcc: S, toAcc: D, amount: int
): MoneyTransferContext[S, D] =
MoneyTransferContext[S, D](
source: fromAcc,
destination: toAcc,
amount: amount
)
proc execute*[S, D](ctx: MoneyTransferContext[S, D]) =
ctx.source.transferTo(ctx.destination, ctx.amount)

Now a single Context handles transfers between completely different Data types while still enforcing Role capabilities at compile time:

main.nim
import accounts, polymorphic_transfer
let checking = CheckingAccount(accountNumber: "CHK-99", balance: 1500)
let visa = CreditCard(cardNumber: "4111-XXXX", currentDebt: 600, creditLimit: 5000)
# Works: CheckingAccount satisfies CanWithdraw, CreditCard satisfies CanDeposit
let payCard = initMoneyTransfer(fromAcc = checking, toAcc = visa, amount = 400)
payCard.execute()
# Compile-time error: CreditCard does not satisfy CanWithdraw!
# let invalid = initMoneyTransfer(fromAcc = visa, toAcc = checking, amount = 100)

2. Do You Need a Custom Macro DSL?

When developers discover Nim’s AST macro system, it is tempting to build a dedicated DCI DSL (for example, context MoneyTransfer: blocks that auto-generate Role types and boilerplate).

In practice, native Nim is almost always the better choice:

The only classic DCI feature that plain Nim omits is implicit Context lookup – allowing one Role method to call another Role in the same Context without passing it as a parameter. Explicitly passing target Roles (source.transferTo(dest, amount)) is clearer, easier to unit test, and avoids hidden Context state.

3. Static vs. Dynamic DCI: Nim vs. Perl

Interestingly, Nim’s UFCS method convention (obj.roleProc(arg) desugaring to roleProc(obj, arg)) mirrors Perl’s classic object model, where methods are simply subroutines whose first argument ($self) is an object reference.

Comparing the two highlights the fundamental trade-off between static and dynamic DCI:

Summary

DCI never needed a dedicated framework in Nim because Nim already separates Data (object) from Behavior (proc). By combining module scoping, distinct types, and concepts, you get readable, use-case-driven architecture with full compile-time safety and zero runtime cost.