Scaling DCI in Nim: Concepts, Macros, and Dynamic Languages

In a production ledger, funds rarely move between identical types. A transfer might debit a CheckingAccount and credit a LoanAccount or ExternalWire. Nim handles polymorphic DCI roles at compile time using concepts – structural interfaces checked statically without inheritance or virtual method tables.

Polymorphic Roles with Nim Concepts

A Nim concept specifies the operations a type must support to play a given role. Any Data type satisfying those expressions qualifies automatically without declaring an implements clause.

polymorphic_transfer.nim
# Roles defined by structural capability rather than inheritance
type
Withdrawable = concept x
x.decreaseBalance(int)
Depositable = concept x
x.increaseBalance(int)
# Data objects remain completely unaware of these concepts
type
CheckingAccount* = ref object
balance*: int
LoanAccount* = ref object
principalOwed*: int
proc decreaseBalance*(self: CheckingAccount, amount: int) =
if self.balance < amount:
raise newException(ValueError, "Insufficient funds")
self.balance -= amount
proc increaseBalance*(self: LoanAccount, amount: int) =
self.principalOwed -= amount
# Interactions work across any matching Data types
proc transferTo[S: Withdrawable, D: Depositable](source: S, dest: D, amount: int) =
source.decreaseBalance(amount)
dest.increaseBalance(amount)

Because CheckingAccount implements decreaseBalance and LoanAccount implements increaseBalance, transferTo compiles into specialised, statically dispatched machine code for that exact pair of types.

Why a Macro DSL Is Unnecessary

Nim offers powerful abstract syntax tree (AST) macros, which tempts engineers to build a custom domain-specific language (DSL) for declaring Roles and Contexts. In practice, native types and procedures outperform a macro DSL:

Compile-Time vs. Runtime Binding: Nim and Perl

Nim’s method convention – treating a.foo(b) as syntactic sugar for foo(a, b) – mirrors Perl, where $obj->method($arg) resolves to a subroutine taking $obj as its first parameter.

Perl can implement DCI dynamically using Role::Tiny->apply_roles_to_object($obj, 'SourceAccount'), which creates an anonymous subclass at runtime and re-blesses the specific instance for the duration of the Context.

Dimension Nim (distinct / concept) Perl (Role::Tiny / my sub)
Role binding time Compile time Runtime
Mismatched role error Build failure before deployment Runtime exception during execution
Memory overhead Zero (identical pointer representation) Anonymous class creation and re-blessing
Best fit Auditable, high-throughput native services Dynamic scripting and runtime composition