Design in Smalltalk. Implement in C.
Mercurius is a community of independent objects: each has a clear responsibility, explicit ownership, and a message to pass onward.
Smalltalk-Style Software Design in C
Cooperating Objects, Message Passing, and the Iron Rules
Mercurius is implemented in plain C, but its design begins from a Smalltalk view of software: a running system is a community of independent objects which collaborate by passing Messages. Each object has identity, limited responsibility, explicit authority, and a well-defined lifetime. Behaviour emerges from their collaboration rather than being concentrated in procedures which know the whole system.
The purpose is not to reproduce class syntax in C. A hierarchy of structures with functions attached would retain the surface appearance of object-oriented programming while gaining little from it. This model is concerned instead with the organisation of behaviour: which object owns a fact, which object may act, which object receives a Message, and which object owns the lifetime of another. Structures, functions, and pointers are simply the material in which that model is expressed.
This paper makes explicit the structural discipline used to build Mercurius:
- the conventions used to talk about objects;
- the Iron rules that govern ownership;
- the standard interface through which an object lives and behaves;
- the Message-passing discipline through which independent objects collaborate;
- the way those rules produce explicit authority and security boundaries.
This is the structural elevation: it describes how any object in this
style must behave. It was written down so that someone encountering the
code could understand, extend, and improve it without reducing the
design to procedural C. Its principles have value beyond that immediate
purpose. Mercurius supplies the examples and evidence, but its concrete
runtime assembly belongs in Architecture.md. Protocol
details and wire formats belong in the RFC, while the mechanical
expression of the model in C belongs in the coding standards.
Contents
- 1. Conventions
- 2. The Iron rules: ownership as law
- 3. Objects, methods, and
Messages
- 3.1 Two traditions of object-oriented design
- 3.2 Messages: how Objects collaborate
- 3.3 Routing, payloads and representation
- 3.4 Message lifetime and acceptance
- 3.5 Keep the method surface small
- 3.6 Nanoclasses: private owned helper Objects
- 3.7 Methods: self-first, verbs last
- 3.8 Naming: big_little_littlest
- 3.9 Design by Contract: bool + errno
- 3.10 A method owns its facts and returns control
- 3.11 Lifecycle and behaviour
- 3.12 Public vs. private methods
- 4. Applying the model to Mercurius
- 5. What the Mercurius example demonstrates
- 6. Applicability beyond Mercurius
- Footnotes
1. Conventions
To keep the description close to the conceptual model, the following conventions are used. Capitalisation identifies terms with a precise meaning in this model; it is not emphasis.
Object means one particular instance with identity, responsibility, and lifetime.
Class means the common role, interface, and behavioural contract shared by Objects of one kind. Named Classes include Transport, Controller, Broker, Session, Compositor, Presenter, and Projector.
Message means a discrete communication constructed by one Object for another.
Lowercase object, class, and message retain their ordinary meanings where the distinction matters.
C implementation names include subsystem prefixes and are written verbatim where needed, for example:
MwsTransport,MwsdController,MwsdBroker,MwsdSession,MwsdCompositor,MwsdPresenter,MwscProjector.When in doubt:
- “A Session asks the Broker…” refers to the conceptual objects.
- “
mwsd_session_createis called bymwsd_broker_create_session…” refers to the concrete C APIs.
The model is defined in terms of these capitalised concepts; the implementation is a faithful realisation of that model in C.
2. The Iron rules: ownership as law
Mercurius is written in C, but the mental model combines Smalltalk-style message passing with an explicit, acyclic ownership and lifetime discipline. C has no notion of ownership or lifetime, so Mercurius adopts four Iron rules which every object must obey.
2.1 The four rules
Whoever creates an object owns it. If a function creates an object (typically via
*_create), the caller becomes its owner and is responsible for eventually destroying it.Ownership never silently changes. If ownership moves from one object to another, that transfer is explicit in the API and in the documentation. No helper function frees a pointer behind a caller’s back.
Borrowers never free what they borrow. Objects often “borrow” references to other objects. Borrowers may use these references but must not destroy the borrowed objects. Only the owner may call
*_destroy.Long‑lived objects own short‑lived ones, never the reverse. The ownership graph must point from long‑lived to short‑lived objects, not the other way around. The Broker owns Sessions; Sessions do not own the Broker. Compositors outlive the Sessions that render through them.
These rules make ownership visible from the architecture diagram. Given two boxes, only the longer‑lived one is allowed to own the shorter‑lived one. No cycles, no “who frees this?” puzzles, and no ability for a transient object (such as a per‑connection Controller) to accidentally control the lifetime of long‑lived state (such as Sessions).
2.2 Why “Iron rules”?
Mercurius uses a Smalltalk‑style object model expressed in plain C.
The discipline reflects its author’s longstanding C and object-oriented practice. Smalltalk is its primary influence: the system is conceived as independent objects collaborating through Messages. Design by Contract is a more specific influence on method obligations and preserved invariants. The intrusive lockable List used throughout Mercurius, for example, dates from 2013. Rust enters the story only as a later point of comparison: when the project was described, someone remarked that its explicit ownership and lifetime reasoning felt “very Rust-like”.
The comparison is useful because Rust has made the vocabulary of ownership and borrowing widely familiar and can enforce many related properties in its type system. The Iron rules express the corresponding concerns as architectural invariants which a C implementation must uphold through design, review, and testing. In Design by Contract terms, they are system-wide invariants: constructors, destructors, and every method which establishes or uses an ownership relationship must preserve them.
So what comes before Rust? Iron.
The name is a small joke, but the rules themselves are serious: they are rigid, load‑bearing, and uncompromising. When the implementation upholds them, the system is substantially easier to reason about and keep predictable. C does not enforce them; a violation remains a defect even when the compiler accepts it.
The Iron rules provide the ownership foundation for a Smalltalk-style object model in a language with no classes, destructors, ownership types, or lifetime checker.
2.3 What this gives you that plain C does not
C is a simple language, and that simplicity is its power. It lets you do anything — which is exactly why its detractors criticise it. C makes it trivially easy to do the wrong thing, and it offers nothing to help you do the right thing. There is no ownership model, no lifetime semantics, no destructor ordering, no prohibition on cycles, and no guardrails against accidental complexity.
But that same simplicity also makes it possible to do the Right Thing — if you bring consistency and discipline instead of expedience. The Iron rules are that consistency and discipline.
C does not track a pointer’s ownership, record when it is borrowed,
or arrange for that borrow to end. None of this happens automatically.
Where a borrow can outlive the operation which supplies it, the design
must make its beginning, end and relationship to destruction explicit.
The optional _borrow and _release methods
described in §3.11 express that obligation; they do not change who owns
the Object or who must destroy it.
They give Mercurius a discipline that plain C does not provide:
A predictable object graph. Every object has one owner, and the ownership graph is acyclic and visible in the architecture. Who must free an object and the intended teardown order can be determined from the design rather than reconstructed from scattered code.
Deterministic lifetimes. Short‑lived components do not own long‑lived ones, and destruction has a well‑defined order. Correct lifetime handling becomes a visible invariant which can be reviewed and tested.
Structured error paths. Constructors, destructors, and ownership boundaries provide one systematic route through partial construction and failure. Leaks and incomplete teardown remain possible implementation defects, but they are violations of explicit postconditions rather than undefined ownership conventions.
Reasonable concurrency. Explicit ownership identifies which object protects which state and makes a locking policy possible to state systematically. The ownership graph is not itself a lock-ordering proof: lock order, cross-object calls, and re-entrancy still require their own declared invariants.
Architectural clarity. The Transport → Controller → Broker → Session pipeline only works if lifetimes are strict, ownership is explicit, and no transient object can destabilise long‑lived state.
In short: the Iron rules let Mercurius pursue the safety and predictability of a higher‑level object system while retaining the performance, portability, and directness of C. They do not turn C into a memory-safe language. They make the ownership and lifetime obligations explicit enough that behaviour under load can be reasoned about, reviewed, and tested rather than left to hope.
3. Objects, methods, and Messages
Smalltalk-style design begins with Objects and their responsibilities. This section explains how they collaborate through Messages, and how C expresses their interfaces, ownership and lifetimes.
3.1 Two traditions of object-oriented design
Class hierarchies organise types and substitutable implementations. Message-oriented design organises collaborating Objects, their responsibilities and the knowledge each needs. These concerns can coexist, but a hierarchy by itself does not establish a community of cooperating Objects. This paper starts with that community and uses C interfaces to express it.
Why Smalltalk is the touchstone
I’m sorry that I long ago coined the term “objects” for this topic because it gets many people to focus on the lesser idea. The big idea is “messaging”. — Alan Kay, Squeak mailing list, October 1998
The Iron rules do not magically turn a C program into a Smalltalk program, nor is “Smalltalk” shorthand here for classes, inheritance, or a language feature which C lacks. Mercurius uses very little inheritance, reserving it for Classes which genuinely share identity, state and policy. Inheritance is not what organises the system. Its Smalltalk character lies in the spirit of the running system: independent objects with identity and limited responsibilities cooperate by passing Messages to one another.
Kay later stated the idea precisely: “OOP to me means only messaging, local retention and protection and hiding of state-process, and extreme late-binding of all things.” (email to Stefan Ram, July 2003)
Classes and inheritance are absent from that definition. The first
two clauses describe this discipline closely. The third is where C needs
care: C binds almost everything at compile time, and Mercurius
deliberately keeps it that way. Late binding is placed where it carries
weight. A sender does not know which object will finally act on its
Message: the binding of a Message to its recipient happens at run time,
as each _handle decides whether to consume or forward it.
Transport is the principal place where an implementation itself is
selected at run time: an abstract base Class whose LOCAL and SCTP
implementations stand behind one fixed protocol.
No individual method appears to do very much, because no individual method is the system. Each object receives a Message, performs the small part for which it has authority, and either consumes the Message or hands it onward. The meaningful behaviour emerges at run time from the collaboration of the whole object community rather than from one procedure which knows and directs every step.
Mercurius makes those collaborations explicit as first-class
MwsMessage objects which may pass through several
_handle methods before reaching their semantic recipients.
This is not a literal reimplementation of the Smalltalk runtime.
Smalltalk is the design touchstone which keeps attention on Messages,
responsibility, and emergent behaviour rather than on the surface
machinery of object-oriented syntax.
Object orientation is not one tradition
Many programmers first meet object orientation through C++, Java, Python, or Rust. That experience can make OO appear to mean attaching methods to data, constructing a class hierarchy, selecting an implementation through virtual dispatch or a trait, and using encapsulation to hide the fields. Those are useful language mechanisms, and Mercurius itself selects its Transport implementation by dispatch, but none of them by itself determines how a running system divides responsibility or how its parts collaborate. A program can use classes, inheritance, traits, and impeccable ownership while remaining a procedural design whose real behaviour lives in a few omniscient routines.
Smalltalk represents another and older emphasis: the running image is a society of objects, and computation proceeds as those objects send messages to one another. Ruby deliberately inherited much of that outlook; its objects respond to messages according to behaviour rather than their position in an elaborate static hierarchy. Python can be designed in the same spirit, even though it is often introduced through classes and method calls. Rust provides powerful ownership, borrowing, enums, and traits, but those facilities answer different questions from “Which object should receive this Message?” and “Where should this authority live?”
Mercurius takes its cue from the Smalltalk and Ruby side of that history while adding the explicit lifetime discipline required by C. Reproducing a C++-like class hierarchy manually would gain little and lose compiler support. The starting point is not a collection of abstract data types with attached functions, vtables and simulated inheritance. Making that machinery the design would reproduce the appearance of Classes while leaving the organisation of responsibility and collaboration unresolved. An operations table may serve a specific substitutable role, as Transport demonstrates; it is a mechanism used by the design, not the source of the design.
The purpose of the Iron rules is not to imitate the syntax of another OO language; it is to preserve independent identity, bounded responsibility, explicit ownership, and Message-driven collaboration in a language which imposes none of them.
3.2 Messages: how Objects collaborate
Mercurius is message-oriented so that the same collaboration works whether the Portal runs on the workstation itself, elsewhere on the same network, or in another country. Objects construct and pass Messages without needing to know where the eventual recipient runs. Location changes the delivery mechanism and its failure modes, not the Objects’ responsibilities or the meaning of their exchange; §3.4 shows how the Message contract absorbs that difference.
The first question when one Object needs something from another is not:
Which function should it call?
It is:
Which Message should it send?
A Mercurius Message represents a discrete communication from one Object to another. The sender constructs the Message and hands it to the next Object on the established routing path. That Object performs only the routing or handling for which it is responsible, then hands the Message onward. The sender need not know which Session, association or Transport carries the Message.
_handle(self, message) is the standard entry point for
this collaboration. When an Object receives a Message, it does one of
two things:
- if it is the intended semantic recipient, it processes the Message according to its own responsibility;
- otherwise, it hands the Message to the next Object responsible for routing it towards its recipient.
Forwarding is therefore not an incidental helper operation. It is
part of the meaning of _handle. An Object may inspect the
universally understood header to decide where the Message belongs, but
an intermediate Object does not interpret or mutate the semantic payload
merely because the Message passed through its handler.
A Presenter shows this in its purest form. When a Window’s geometry
changes, it constructs MWS_RENDER_PRESENT and gives it to
its parent Compositor:
/* Give the message to our parent compositor */
return mwsd_compositor_send(self->compositor, &message);That is all it does, and it is where its responsibility ends. The Presenter knows the Window’s geometry, the Message which carries the update, and its parent. It does not know what a Projector is, nor anything of Portals, Sessions, associations, streams, or Transports. Wherever the update is eventually projected, the Presenter neither knows nor needs to.
The only thing the Presenter shares with the Projector is the Message
itself. One produces the MWS_RENDER_PRESENT payload and the
other consumes it, so the two evolve that payload in lockstep.
Intervening Objects use the header and ask the Message for routing
fields such as window_id; Session must not extract that
identifier from the payload itself. Every other Object on the path
leaves the semantic payload opaque. The sender and receiver are coupled
through the Message, never through each other.
3.3 Routing, payloads and representation
The Message header is universally understood and identifies the Message type and extent. Routing also uses context established by the Object path: a Transport supplies association context and a Controller selects a Session.
Some fields are needed for routing but do not belong in the common
header, because most Messages do not carry them. The Window identifier
is the clearest example: Session must not interpret the payload, so it
asks the Message for the window_id of the Window the
Message concerns. A Seat identifier and other routing fields of the same
kind follow the same rule.
Intermediate Objects rely on Message alone to locate and decode these fields. That knowledge is a constraint on the sender and receiver. Within the applicable protocol contract, they are otherwise free to arrange the payload between them however their exchange requires, because it is opaque to every other Object. They must not, however, disturb the routing fields on which the rest of the Object graph depends. Those fields belong to the routing contract, not to the semantic exchange.
A routing query exposes only the requested routing fact, leaving its
representation encapsulated and the semantic payload opaque. A Message
concerning a Window need not be sent to the Window Object itself; any
Objects may exchange such a Message when that collaboration belongs to
their responsibilities. Ask a Window for its own window_id;
ask a Message for the window_id of the Window it
concerns.
Beyond its routing fields, the payload belongs to the semantic exchange between the Objects that produce and consume the Message. An opcode does not by itself imply one universal semantic payload format. The applicable protocol contract defines the representation needed for interoperability, including any common envelope or routing fields.
The final recipient recognises the conversation to which the Message belongs from the established Object path, the Message’s internal metadata, and any correlation information defined by the applicable protocol contract. It interprets the payload in that context. Where the contract permits conversation-specific detail, the same opcode may carry different details between different Objects, or between the same Objects in different conversations.
MWS_ERROR_RESOURCE is the canonical example. The opcode reports the broad fact that lack of a required resource prevented some work, but the useful information depends on the conversation to which it replies. The sender reports the facts it owns; the final recipient uses those facts, together with its knowledge of the conversation, to decide whether it can retry, choose another approach, propagate the failure, or abandon the operation.
Intermediate Objects treat the remaining payload as opaque. They use the header, routing fields and their relationships with neighbouring Objects to pass the Message onward; they do not interpret, mutate or consume its semantic content. Objects which move Messages, such as Transport and Sender, may copy and encode payload bytes. Moving bytes is not interpreting them. This allows collaborating Objects to evolve their exchange within the applicable protocol contract without teaching the entire Object graph about it.
Bytes and meaning
The collaborating Objects also protect the boundary between bytes and meaning. A workstation and Portal need not be implemented in the same language: a C workstation, Ruby Portal, and Rust Portal must all exchange the same Message. The protocol representation is therefore language-neutral and never inherits the native object, array, alignment, padding, or type rules of one implementation language.
Consequently, a received payload is not a C array or structure merely because its documented fields have those types. Questions about the common header and the explicitly documented routing prefixes belong to the Message. Questions about a particular payload belong to the Object expected to understand it: an Error, for example, validates and decodes the common Error envelope. That Object validates the complete byte representation and copies fields into aligned typed values; it does not cast Mallory’s1 bytes and interpret them as native C objects. The Message may provide representation-neutral methods which assist with that deserialisation, but those methods do not know what the payload means. Conversely, a C sender may construct a genuinely typed array and hand its byte representation to a Message. This asymmetry is intentional: construction begins with known values, while decoding begins with a language-neutral and potentially hostile byte sequence.
MWS_AUTH_RESPONSE illustrates this clearly. The response
is meaningful to the Authenticator, not to the objects which carry it
there. The Authenticator consumes the Message and destroys its sensitive
contents with explicit_bzero; no intermediate object needs
to understand them.
Messages are not wire packets
Some Messages cross the network and some deliberately do not. This
does not change the object model. MWS_RENDER_UPLOAD, for
example, is an internal Application-to-Window Message on the server
side. Application does not call a Presenter function simply because both
objects ultimately execute on the same machine. The Message follows the
real object path, allowing Window, Compositor, and Presenter to retain
their separate responsibilities.
Messages expected to pass between Objects within the same process use
the same MwsMessage container and
_handle(self, message) contract as any other exchange. They
do not need a separate Message type or private framing protocol. A
message type identifies a collaboration, not a process or network
boundary. Each receiver determines which Messages it can accept. Moving
a receiver into another process or onto another machine changes delivery
and may require a serialisable payload representation, but does not
change the collaboration or justify bypassing its Message path.
Ownership and payload lifetime remain explicit even when delivery is a
synchronous method call.
That path is also a security boundary. The Channel belongs to an Application, the Application belongs to exactly one Session, and the Session resolves the Message’s Window identifier only within its own Window collection. No current transport association is required for that internal authority path. A direct Application-to-Presenter call would bypass this structural routing and make it much easier for one Application to reach a Window belonging to another Session. Message passing therefore preserves the isolation which prevents Eve or Mallory from capturing Alice’s or Bob’s Windows, as well as avoiding implementation coupling between Application and Presenter.
3.4 Message lifetime and acceptance
A Message expresses a collaboration, but passing it does not silently transfer ownership of either the Message or its payload. The method contract must state what is borrowed, what is copied, and whether any ownership is explicitly transferred. This is the Iron rules applied to communication.
In C, a Message and its payload storage can have different lifetimes. A sender may construct a Message on its stack whose payload refers to another buffer. A decoded Message may likewise refer into a receive buffer owned by its caller. Copying the Message copies those references; it does not copy the bytes or extend the lifetime of their owner.
For synchronous handling, the caller keeps the Message and its payload valid throughout the call. A receiver which needs the data afterward must establish a lifetime for its retained data before returning. It can copy the required bytes into storage it owns, or acquire an explicitly supported tracked borrow of the payload owner. A receiver must never retain an unprotected reference into a caller’s stack or reusable receive buffer. A tracked borrow protects lifetime; it does not by itself prevent the owner from changing the bytes. The contract must also preserve the content on which the retained operation relies.
Mercurius provides both patterns. A Message whose payload has an
explicit lease can be retained through mws_message_borrow,
which copies it into the receiver’s own Message storage and registers a
borrow of the payload owner; mws_message_release later ends
that borrow. Once the borrow is established, the original Message need
not remain alive. A Portal Sender instead encodes the Message into
storage it owns before admitting it to its worker’s queue. Encoding
gives the queued Message independent byte storage; tracked borrowing
instead preserves an explicitly protected dependency on the payload
owner.
The Sender’s encoded copy retains neither the caller’s payload pointer nor the Message’s sender Object pointer. A retained Message copy may carry the sender pointer, but its payload borrow does not protect the sender’s lifetime. Any later use of that pointer requires separate, documented lifetime protection. The same applies to any retained reference to an Object, including a reply recipient.
Acceptance and completion are different facts. A true
return from _handle means that the receiving Object
fulfilled its handling contract: it processed the Message, passed it
onward, or accepted responsibility for later work. It does not by itself
establish that the requested operation has completed. A
false return reports failure to fulfil that contract, with
errno explaining why; it does not prescribe the caller’s
recovery policy.
Failure does not silently transfer ownership. It also does not necessarily mean that no work was accepted or no state was retained: an error can occur after admission. The handling contract must state what work or retained state can remain when failure is reported, so that the caller can respond without assuming that retrying is harmless.
Consider the Portal Sender’s successful admission of an outbound Message:
caller constructs a Message using storage it owns
caller passes the Message to Sender
Sender validates and encodes an owned copy, then admits it to its queue
Sender returns acceptance; caller may now release its original storage
Sender's worker attempts delivery using the owned copy
Sender makes any later delivery failure observable to the wider collaboration
Sender releases the owned copy when that delivery attempt is settled
The successful handling call establishes admission, not Transport delivery or the remote recipient’s completion. The wider collaboration must define how those later outcomes become known: through a reply Message, a documented completion notification, or an explicit failure query. Sender uses its check method to expose delivery failures. A reply is itself a new Message with its own ownership and lifetime contract.
Neither acceptance nor deferred completion permits an Object to destroy state still required to fulfil the responsibility it has accepted. A Class may use a private nanoclass to implement deferred work, while remaining responsible for its lifetime and outcomes (§3.6).
3.5 Keep the method surface small
Every non-trivial Class exposes the standard lifecycle and
behavioural interface defined in §3.11, of which _create,
_destroy and _handle are mandatory. Those
standard method forms provide a stable core; what grows a Class’s
surface is everything added beside it. A Class may have domain-specific
methods where ownership, local inspection, or an intrinsic operation
makes a direct call the honest interface.
Those methods should be as few as the Class can reasonably have without contortion. A convenience method that reaches across an Object boundary is not harmless: it adds coupling and encourages the system to become a collection of procedures acting on structs. Before adding one, ask whether the operation is really a Message that should travel between cooperating Objects.
Orchestration, not omniscience
Orchestration is legitimate when coordinating a sequence is itself part of the Object’s responsibility. The test is not method length, and it is not whether a method calls several helpers. The test is whether the orchestrator owns the operation and composes bounded steps without taking decisions, state, or authority which belong to another Object (§3.10).
Consider an operation which must acquire temporary resources, transform them through several ordered stages, produce one result, and then release every intermediate resource. The owning Object’s orchestration method should read as that one operation: establish the temporary state, perform the bounded stages, settle the operation’s result, unconditionally tear the temporary state down, and report the outcome, accounting for any cleanup failure. The stages may be private methods when each owns a real fact or invariant; they should not be extracted merely to make the orchestrator shorter. Where the temporary state itself has invariants and a lifetime of its own, a nanoclass may provide the private Object boundary which enforces them (§3.6).
What the model resists is not orchestration but omniscience: a method which coordinates distant Objects by reaching through their boundaries, interprets Messages which belong to them, or accumulates enough foreign knowledge to become the real system in procedural disguise. Larger system behaviour should still emerge from cooperating Objects observed together at run time.
3.6 Nanoclasses: private owned helper Objects
A C struct groups fields. That alone establishes neither
ownership nor a resource-lifetime contract; it remains passive storage
whose correct use must be reconstructed from the surrounding
procedures.
A struct becomes a nanoclass when the design gives it a coherent private responsibility, explicit ownership and a lifecycle which preserves its invariants. A nanoclass is a helper Object private to one instance of a larger Class. It represents a part of that Object which has state, resources, invariants and a lifetime of its own, but no independent role in the wider Object community.
Sole ownership is necessary but does not distinguish a nanoclass from a full Class: a full Class can also have exactly one owner. The distinction is how Objects collaborate with it. Other Objects address a full Class through its own interface because it has a responsibility towards them. A nanoclass implements part of its owner’s responsibility; other Objects collaborate with the owner, while the helper’s concrete identity and organisation remain private.
The Iron rules apply at this smaller scale:
- The larger Object is the sole owner and holds the sole owning reference.
- A constructor establishes every invariant or leaves no live nanoclass.
- A destructor releases every resource the nanoclass owns; the owner then clears its reference.
- The owner’s destructor destroys the nanoclass before the owner’s own storage is reclaimed.
- Failure paths after construction converge on the same destructor.
- Private methods preserve the invariants established by construction.
The constructor and destructor are therefore not allocation wrappers added for symmetry. They are the boundary which turns an incidental collection of fields into an Object with a provable lifetime. Whether the storage is allocated separately, embedded in its owner, or created only for one operation is secondary; ownership and teardown must remain unambiguous.
A nanoclass is normally declared and implemented in its owner’s
private implementation file. It ordinarily needs no public header, class
tag, global registry, or independent Message interface. Its method names
pass through the owning Class, such as
mwsc_auth_sshkey_create, making the relationship visible
rather than presenting the helper as a new top-level subsystem. Private
linkage does not remove validation obligations: methods receiving the
owner validate that Object, and methods receiving the helper validate it
according to its own contract (§3.7).
An owning operation using a temporary helper synchronously follows this shape:
create private helper
if creation failed, return failure
perform the coherent operation through the owner and helper
once the operation has succeeded or definitively failed:
remember its result and, if it failed, its error
destroy private helper unconditionally
remember any destruction failure
if the operation failed:
report any additional destruction failure separately
restore the operation's error
return failure
if destruction failed, return failure with the destruction error
return success
The operation’s result must be settled before destruction begins, so success and every post-construction failure follow the same cleanup path. Cleanup is part of the owner’s responsibility: successful work followed by failed destruction must not be reported as complete success. If both fail, preserve the operation’s error and report the destruction failure separately through the owner’s diagnostic path. Destruction ends ownership irrespective of its result; the former pointer must not be reused or passed to the destructor again.
A nanoclass may retain state across calls or own a worker where that work remains private to the owner. The owner establishes its lifetime, coordinates its shutdown and remains responsible for its outcomes. Application’s private Executor, for example, owns a completion worker without acquiring a separate role outside Application. A payload lease may likewise protect a private helper’s lifetime without exposing its concrete identity or making it an independent semantic recipient. The owner’s destructor remains the final backstop, coordinating outstanding work before reclaiming the state it needs.
A helper becomes a full Class when the design gives it a distinct
role through which other Objects collaborate with it. Neither size nor
the presence of a _run method determines that boundary. A
Class tag or separate allocation may support an implementation, but
neither establishes an independent role.
Small size alone does not justify a nanoclass. A few fields grouped for convenience, or a block split into functions merely to shorten its caller, has not acquired a separate responsibility or lifetime. Turning such fragments into helpers adds ceremony and forces readers to mentally reassemble a linear operation. A nanoclass is warranted only when its constructor, destructor, state, and behaviour together enforce a real private boundary.
This is the practical meaning of the mantra:
Design in Smalltalk. Implement in C.
3.7 Methods: self-first, verbs last
Non-trivial functions are treated as methods on Objects:
- Except for constructors, the first parameter is always the Object,
named
self. - The name ends with the action the method performs, the littlest part
of its big_little_littlest name (§3.8). Lifecycle and behaviour use
single verbs:
*_create,*_destroy,*_handle,*_process,*_run,*_borrow,*_release. Other actions are verb phrases naming what they act upon:*_add_window,*_attach_session,*_create_session,*_run_handshake,*_extract_window_id. Getters use*_get_something, naming the fact returned.
The code reads in terms of Objects and verbs rather than in terms of raw functions and global state.
A method call is not, however, merely another spelling of a Mercurius Message. Methods provide an Object’s lifecycle and behavioural interface; Messages are how independent Objects collaborate. Keeping that distinction clear is essential. Otherwise a collection of structs with functions attached can look object-oriented while remaining a procedural call graph underneath.
Why this rule exists
This convention is not aesthetic, historical, or merely because
Smalltalk methods take self. It exists because the system
manages zero or more live Objects of each Class: Handshakes, Sessions,
Windows, Transports and others. Each instance has its own identity,
state and lifetime. Handshakes, for example, may progress independently
for many Portals at once.
Mercurius’s SCTP Transport provides a practical example. Changing
from one Transport per interface to one per bound address required no
change to the model: each instance already carried its own identity and
state. Methods continued to act on the Transport passed as
self, regardless of how many instances existed.
By requiring every method other than a constructor to take
self:
- the instance on which a method operates is always explicit;
- no global or implicit “current Object” is ever needed;
- each Object can be exercised and tested in isolation;
- concurrency and interleaving can be reasoned about per instance;
- the code scales naturally to many simultaneous Objects.
C does not enforce Object boundaries. Explicit receivers make instance boundaries visible in ordinary C interfaces.
The receiver gate comes first
C cannot establish that self identifies an Object of the
expected Class, so every method with a receiver begins by asking the
Object runtime. This is not merely ordinary C argument checking. It is
the gate which decides whether the call has reached an Object of a Class
able to act on it:
if (!mws_object_is(self, MWSD_CLASS_PRESENTER))
{
errno = EINVAL;
return false;
}mws_object_is is NULL-safe: NULL identifies no Object
and therefore matches no Class. The receiver gate rejects both NULL and
a receiver with the wrong Class tag. Destructors test NULL first because
their contract treats absence as success.
Given a pointer whose lifetime is already protected, the gate checks that the receiver has the expected Class tag. It does not prove that this is the intended instance of that Class. It also cannot establish that an arbitrary pointer is safe to dereference or that the Object is still alive; those guarantees come from ownership and protected borrowing (§3.11).
Nothing belonging to the implementation of the method precedes that gate, not even declarations of local working state. Only after the receiver has been established does the method begin constructing the state needed to fulfil its responsibility. Variables required by a shared cleanup path are declared and initialised immediately after receiver and argument validation, before any path can enter that cleanup. This retains C’s necessary cleanup discipline without putting procedural machinery ahead of the Object.
Constructors have no receiver to gate. They validate their arguments
first and report failure by returning the Class’s typed absence
sentinel, such as MWSD_PRESENTER_NONE (an alias for NULL),
with errno set. Private nanoclass methods follow the same
validation discipline: a method receiving the owner validates that
Object; one receiving the helper validates it according to the helper’s
contract (§3.6).
Destructors have one documented pre-gate case.
self == NULL means there is nothing to destroy, so the
destructor has already achieved its postcondition:
if (self == NULL)
{
return true;
}
if (!mws_object_is(self, MWSD_CLASS_PRESENTER))
{
errno = EINVAL;
return false;
}The NULL test expresses the destructor contract; it is not method-local setup. Every non-NULL receiver is still validated before the destructor declares or constructs working state.
3.8 Naming: big_little_littlest
Every function name follows a big_little_littlest pattern:
big: the subsystem prefix:
mwsc_: the Portal (themwscprogram);mwsd_: the server daemon (themwsdprogram);mws_: the shared protocol and Transport layer.
little: the Class, followed where applicable by a concrete implementation or private nanoclass within it:
mwsd_session_,mwsd_broker_,mwsc_control_,mws_transport_,mws_transport_sctp_.littlest: the action, a verb or verb phrase:
mwsc_control_run_handshake,mwsd_session_add_window,mwsd_broker_attach_session,mws_transport_destroy.
Once the Object and the action are known, the symbol name is usually obvious:
- “Server daemon Session add window” →
mwsd_session_add_window. - “Portal Control run” →
mwsc_control_run. - “Destroy a Transport” →
mws_transport_destroy.
This makes the code easy to search. Searching for
mwsd_session_ finds the Session Class’s methods and their
uses; mws_transport_sctp_ selects the SCTP implementation
and its private helpers; _attach_session finds attachment
methods and their call sites.
3.9 Design by Contract: bool + errno
Smalltalk shapes how Mercurius Objects collaborate. Design by Contract, associated with Bertrand Meyer and Eiffel, supplies another part of the object-oriented tradition: making the obligations between a caller and an Object explicit. These ideas are complementary. Messages establish the collaboration; contracts establish what each participant may require and what it promises in return. The Iron rules supply the ownership and lifetime discipline needed to realise those promises in C.
Objects and contracts
Eiffel Software’s introduction, Building bug-free O-O software, describes the essential information in a routine’s contract as:
what each party in the contract must guarantee for a correct call, and what each party is entitled to in return.
— An Introduction to Design by Contract, §3.
An Object’s interface is a set of promises on which other Objects can rely without knowing its implementation. A method name and parameter types identify an operation, but cannot by themselves say when it is valid, what it achieves, or what remains true afterward. Design by Contract makes those questions part of the design through three kinds of assertion:
- Preconditions describe what the caller must establish before invoking the method: a protected receiver, valid arguments, and any required state.
- Postconditions describe what the method guarantees on successful completion: the result produced or the state established.
- Class invariants describe the conditions which make an instance a valid Object and which its methods must preserve at their externally observable boundaries.
These are reciprocal obligations. A caller which meets the preconditions is entitled to the promised result; the receiving Object may rely on those preconditions when doing its work. An invariant connects the individual methods: each leaves the Object fit for the next valid operation. Eiffel provides language facilities for expressing these contracts directly; its Design by Contract documentation describes this relationship between callers and routines.
This view of OO gives an Object responsibility for maintaining a valid state and fulfilling its promises. Its callers need to understand the contract, rather than reconstructing that state from its fields or following its implementation. It applies both to Objects collaborating through Messages and to the lifecycle and intrinsic operations exposed through methods. Contracts remain useful whether or not the design uses inheritance.
Mercurius applies this discipline to every method, public or private. C cannot express the contracts as Eiffel does, so they are stated in method documentation and realised through validation, implementation and tests. The failure contract is explicit too: a method which cannot establish its success postcondition reports failure while preserving the Object’s invariants, unless its contract explicitly ends the Object’s lifetime or ownership.
C has no built-in Design by Contract facility, so the method checks
its own preconditions. Passing the wrong Object or an invalid argument
is a caller defect. The method reports it through its documented failure
value with errno set to EINVAL, before
performing the requested operation, so the defect is apparent at the
call which caused it rather than surfacing later as undefined behaviour.
This validation presupposes the protected pointer lifetime described in
§3.7. Hostile input is a different matter: bytes received from a peer
are validated as data by the Object which understands them (§3.3).
Why bool + errno
The contract defines success; bool reports whether that
success was achieved. If the method returns false,
errno explains why it could not fulfil its promise, while
its documented failure contract states what remains valid. The caller
receives those facts and retains responsibility for deciding what
happens next.
Mercurius deliberately uses bool for the success or
failure of a behavioural method, with errno supplying the
reason for failure. This is a project convention, not a claim that C
interfaces generally follow this shape. C interfaces use several
conventions: zero may mean success, a negative value may mean failure,
or a return value may combine a useful result with a special failure
value. Mercurius gives its own methods one consistent reading:
true means that the method fulfilled its responsibility;
false means that it could not, and requires an explanation
in errno.
The choice separates three facts which would otherwise compete for the return value:
- whether the method performed its responsibility;
- why it failed to do so;
- what result its work produced.
The first belongs in the bool return, the second in
errno, and the third in an explicit output, Object state,
or reply Message according to the method contract. A lookup can succeed
and find nothing; an authentication check can succeed and deny access.
Neither outcome needs to masquerade as a failure to perform the work.
Constructors and getters have the specific return contracts below
because producing an Object or returning a fact is their purpose.
Using bool makes the success test read the same way at
each Object boundary, without requiring the caller to remember whether
this particular method uses zero, minus one, or some other value. Using
errno gives failures a common vocabulary which can also
describe failures of the C and operating-system facilities used to
implement the method. A method translates those facilities’ return
conventions at its boundary: a library’s zero-on-success result is not
passed through as a Mercurius boolean, nor is an error number returned
by a library assumed to have set errno.
The reason must describe the failure accurately. EINVAL
identifies an invalid receiver or argument; it is not a substitute for a
more precise resource, I/O, or protocol error. A method propagating
another method’s failure preserves its reason unless its own contract
requires a meaningful translation. It does not replace useful evidence
with a generic error.
This convention reports facts while leaving recovery with the caller
(§3.10). The return value does not instruct the caller to retry, abandon
its operation, or shut down. Nor does false imply that the
method made no changes: the contract must state the valid state and any
retained responsibility left after failure. Those are ownership and
behavioural guarantees, not properties which a boolean can establish by
itself.
The return contracts
Every method which can fail, public or private, follows the same basic contract:
Constructors (
*_create(...)) Return a pointer to a fully initialised Object on success, or the Class’s typed absence sentinel, such asMWSD_PRESENTER_NONE(an alias for NULL), on failure witherrnoset.Behavioural methods
- Return
bool:trueon success;falseon failure, witherrnoset to an errno-compatible value describing the error.
- Require
selfto identify a valid Object of the expected Class.
- Return
Getters (
*_get_something(...)) Return the requested fact directly, or a documented sentinel on failure witherrnoset. If a sentinel also represents ordinary absence, the contract must distinguish that successful outcome from failure unambiguously; callers must not infer failure from a staleerrnovalue.Destructors
- Alone are safe to call with
self == NULL. - Return
truewhen ownership has ended and immediate teardown succeeded. - Return
falsewitherrnoset if immediate teardown failed. - End ownership in either case; the owner must never reuse or retry
the former pointer. Where tracked borrows defer reclamation, its outcome
is reported by the final
_release(§3.11).
- Alone are safe to call with
The uniform contract means:
- “Did this work?” → check the documented return value.
- “Why did it fail?” → check
errno, and only after a failure.
errno belongs to the failed call
A successful method does not clear errno. Its value may
still describe an earlier failure, so a caller must first inspect the
documented return value. Only a failure makes errno an
explanation of this call. Each failing method must establish that
explanation; it must not return false while leaving an
unrelated error behind.
The caller reads or saves the error before calling anything which may replace it, including cleanup or diagnostic code. If an operation fails and cleanup also fails, the original operation’s error remains the primary result; the cleanup failure is reported separately (§3.6). This is how a single error channel remains useful across a chain of Objects: each boundary preserves the fact it is reporting rather than accidentally reporting the last function called.
errno accompanies a method return; it is not a stored
outcome for work which continues after that return. A worker’s later
failure must become observable through the collaboration’s documented
reply, notification, or failure query (§3.4). Likewise,
bool + errno carries a failure category, not an entire
diagnostic report. Any additional context or structured result belongs
in the explicit interface which needs it.
Failure is not refusal
Here bool reports whether the method fulfilled its
contract. It is not normally the answer to a question in the
application’s problem domain. An Authenticator can report: “I have
successfully considered your request, and no, you can’t come in.” It
returns true because consideration succeeded; the refusal
is conveyed through a separate decision output or a reply Message. The
two questions have separate answers: whether the Authenticator completed
its consideration, and whether it granted access. Returning
false with errno means that it could not
complete that consideration; it does not mean that it successfully
decided to refuse access. Likewise, “not found”, “not accepted”, and
“unchanged” require an explicit result when they are ordinary outcomes
rather than failures. This keeps “something went wrong” clearly
separated from “computer says no”: false means the method
failed to fulfil its responsibility, and errno explains
why. For Message handling, that responsibility is distinct from the
eventual requested operation’s completion (§3.4).
NULL and destruction
NULL-tolerance is not a general property of methods. A behavioural
method has no Object on which to operate when self == NULL,
and treating that as success would conceal a caller error. The exception
exists only for destruction and serves the ownership and teardown rules
described in §3.10.
A destructor failure is exceptional and serious, but it must remain
observable. A destructor which encounters one release failure continues
releasing the other resources it can reclaim rather than returning early
and leaving a half-destroyed Object graph. Resources protected by
outstanding tracked borrows remain valid until final reclamation
(§3.11). The destructor returns false with
errno set for an immediate teardown failure, so the caller
can preserve a useful diagnostic and report the failure while continuing
its own cleanup. The return value does not preserve the Object for
another attempt. Whether a failure requires abandoning an operation or
shutting down a larger part of the system belongs to the caller’s
responsibility (§3.10).
A constructed Object is always safe to use
If _create returns an Object, every public method of
that Object is safe to call until _destroy is called,
subject to the lifetime and concurrency obligations of its contract.
Safe does not mean that every operation must succeed. The method must
validate its arguments and current Object state, then either perform its
responsibility or fail cleanly according to its declared contract. It
must not invoke undefined behaviour or depend on the caller knowing an
undocumented fragment of its construction history.
Lifecycle dependencies remain legitimate. A Transport may need to be
opened before it can carry a Message; a state machine may accept an
operation only in one phase; a resource may not yet have been bound.
Calling the corresponding method too early or in the wrong state is
nevertheless non-fatal: the method reports failure through its
documented return value with errno set and leaves the
Object in a valid state.
A Message arriving out of phase from a peer is a protocol matter. A
handler may reject it with false and EPROTO,
which its caller translates into the appropriate protocol error. A
successfully handled refusal may instead be conveyed through a reply
Message. The handling contract defines which outcome the receiver is
responsible for reporting.
This guarantee begins at the constructor boundary. A constructor must
either return a fully initialised Object whose invariants hold,
including explicit sentinel values for resources not yet acquired, or
clean up internally and return the Class’s typed absence sentinel with
errno set. A partially initialised Object is never handed
to its caller. After _destroy returns, the former owner
must never use its pointer again. An Object with tracked borrows remains
physically alive for those borrowers until the final
_release, as specified in §3.11.
3.10 A method owns its facts and returns control
The contract and return convention of §3.9 give the caller reliable facts about a method’s outcome. Responsibility determines what the caller should do with them. The method knows its own work; its caller knows why that work was requested and how its outcome affects the operation the caller owns.
Objects use methods for lifecycle, intrinsic operations, and for accepting or handing onward Messages. Each method has a well-defined responsibility and a limited view of the system. It therefore reports only the facts that arise from performing its own work.
A method owns its facts; it does not own its caller’s decisions.
When a method returns, it reports what it knows:
- whether it successfully performed its own responsibilities;
- if not, why it could not;
- any results produced by the operation.
These facts describe the outcome of the method itself. They do not prescribe what should happen next. The caller may retry where the failure contract permits it, choose an alternative, report the outcome elsewhere, or decide that no further action is required. Its decision follows from its own responsibility and the wider context in which it operates.
A method may retry an action as part of fulfilling its own responsibility, within its documented limits. Once its outcome is settled, it reports the facts and returns control. It must not decide how its caller should recover or take authority belonging to another Object.
Failure follows responsibility
A low-level failure need not end the system. Its caller may be able to fulfil its own contract through another route. If it cannot, it settles the work it owns, performs the required cleanup, and reports its own failure while preserving the reason. At each boundary, the Object with the relevant responsibility decides whether recovery remains possible.
When an unrecoverable failure propagates through the Object graph, each owner can release its resources in order while preserving the reason for failure. The result is an orderly unsuccessful shutdown with useful diagnostics. This behaviour follows from the combination of explicit failure contracts, ownership and returned control: the failure remains observable, and cleanup is performed by the Objects which know what they own.
The same separation applies to successful work. Higher-level behaviour emerges from cooperating Objects, each fulfilling its own responsibility, rather than from a method making assumptions about its callers’ intentions.
Success is the postcondition
A method’s postcondition defines success; the caller must not be
required to prove incidental facts in order to discharge its
responsibility. An operation whose contract requires a particular state
has succeeded if that state already holds. A _destroy
called with a cleared, NULL child slot, or a method asked to ensure that
an already absent path is removed, has done its job: the thing the
caller needed gone is gone. NULL tolerance does not permit repeated
destruction through a stale pointer. Returning failure for such a no-op
reports the wrong fact.
The two destructor rules are opposite sides of the same invariant:
A destructor must end ownership and arrange complete resource reclamation, preserving resources still protected by tracked borrows. An owner must be able to call the destructor for every child unconditionally.
This is why destructors, and only destructors, accept NULL. An owner
must not have to reconstruct the history of a partially created or
partially torn-down object before it can destroy it. Some children may
not yet have been created; others may already have been destroyed on an
earlier path and their pointers cleared. The owner’s destructor can call
_destroy on every child slot in ownership order without a
ladder of tests for which earlier operations did or did not occur.
A destructor receiving NULL has nothing to release, so its
postcondition already holds. This is a small, deliberate exception to
the rule that a method acts on an object identified by
self, justified by the stronger rule that an owner’s
destructor must reliably release the complete object graph beneath
it.
3.11 Lifecycle and behaviour
Every non-trivial Class exposes _create,
_destroy and _handle. These are the only
mandatory interfaces. _process and _run apply
where the Class has corresponding behaviour; _borrow and
_release apply where it must explicitly track borrows. A
Class with no such borrowers needs neither method. Private nanoclasses
retain the internal lifecycle described in §3.6; they do not acquire an
independent public Message interface.
These methods define how an Object is created, collaborates, performs its own work, lends access to borrowers when needed, and is eventually destroyed under the Iron rules.
*_create(...)Allocate and fully initialise an Object. Establish all invariants. The caller becomes the Object’s owner. Failure is reported as described in §3.9.*_destroy(self)Retire the Object: end ownership, close admission to new tracked borrows, and arrange resource reclamation. Safe to call withself == NULL(see §3.10). Must not release resources it borrows from other Objects. Any teardown collaboration with those Objects goes through their interfaces and respects their lifetime and authority boundaries. Must continue teardown after an individual release failure and reportfalsewitherrnoset if complete release could not be achieved. May wait for what the Object owns, such as a worker thread it must stop and join, but never waits for outstanding borrowers. Without outstanding borrows, reclamation is immediate. Otherwise the storage and resources borrowers may access, including the class tag their_releasewill check, remain valid until the final_releasereclaims them. The former owner must never use the Object again, irrespective of the return value. The return value reports immediate teardown failures; deferred failures are reported by the final_release.*_handle(self, message)Receive oneMwsMessagethrough the Object’s standard Message interface. Requires a validselfof the expected Class and a valid Message. Atruereturn confirms that the Object received and understood the Message and fulfilled its handling responsibility. It does not confirm that the action requested by the Message was taken. Handling may mean forwarding the Message, accepting deferred work, or replying with a refusal. Failure to fulfil the handling contract is reported asfalsewitherrnoset. If the Object is the intended recipient, it processes the Message according to its own responsibility. Otherwise it hands the Message to the appropriate next Object for onward routing. A routing Object may inspect the Message header and ask the Message for its routing fields, but must not interpret or mutate a payload belonging to another semantic exchange. Ownership, retention and the distinction between acceptance and completion follow the Message contract described in §3.4.For example,
_handlemay returntrueforMWS_CREATE_WINDOWto confirm that it received and understood the Message, without confirming that a Window was created. Later, anMWS_WINDOW_CREATEDMessage may report that outcome. The standard Message header includes asenderfield for directing such a reply to the original sender. A reply is a separate Message, with its own lifetime contract; retaining a reference to its recipient requires the protection described in §3.4.A Class expecting no semantic Messages still provides this entry point: it validates both arguments and returns success without changing state. Requiring
_handlekeeps Message passing visible as the default way to extend collaboration between Objects. When a new interaction is needed, the first question is which Message expresses it. A direct method is appropriate where ownership, local inspection or an intrinsic operation makes a direct call the honest interface (§3.5); it should not be added merely to bypass a collaboration which belongs in a Message.*_process(self, ...)Advance an internal state machine or perform a bounded unit of work. Requires a validselfof the expected Class._processis used when the Object has a protocol or state machine that progresses step by step, such as handshake phases or visibility transitions. It must return promptly and must not loop indefinitely.*_run(self)Execute long-running behaviour such as an event loop, Message pump, or background task. Requires a validselfof the expected Class._runis typically the body of a thread owned by the Object. It may block on file descriptors, wait queues, or timers, but must never violate ownership boundaries. Objects that own threads, such as Channel and Projector, implement their long-lived behaviour here. Assigning independent threads to different Objects allows high-priority tasks, such as processing input or streaming audio, to run promptly without being blocked by long-running operations like rendering.*_borrow(self), optional and paired with_release. Register a borrow of a live Object without transferring ownership. Requires a validselfof the expected Class and an Object still accepting borrows. Returnstruewhen the borrow has been established, orfalsewitherrnoset and no new borrow. Each successful call requires exactly one matching_release, including on failure paths in the borrowing operation.*_release(self), optional and paired with_borrow. End one established borrow. Requires a validselfof the expected Class and a matching outstanding borrow. Returnstruewhen that borrow has ended, orfalsewitherrnoset when the contract cannot be fulfilled. The caller must not continue using the Object through that borrow after releasing it. Releasing the last borrow of a retired Object performs final reclamation. This does not transfer ownership or authorise the borrower to call_destroy. A valid borrow is consumed even if final reclamation reports failure; the releasing caller must report that failure through the documented diagnostic mechanism and must not release again.
Explicit borrowing and ownership
_create and _destroy describe ownership.
_borrow and _release describe permission to
use an existing Object for a bounded lifetime. The distinction is
similar to List separating _create/_destroy
from _init/_fini: different lifetime
responsibilities deserve different names even when they share private
implementation. Only the owner retires the Object; a borrow does not
confer that authority. Reference counting may implement deferred
reclamation without creating shared ownership.
A synchronous borrowed argument often needs no registration: the
caller already keeps the Object alive for the complete method call. An
asynchronous Message recipient, queued operation or worker may need to
keep using an Object after that call returns. Where those borrows need
tracking, _borrow and _release make the
obligation visible in code. They are added for that responsibility, not
retrofitted to every Class or every pointer argument.
The owner must keep the Object alive while a borrower establishes its
borrow. Calling _borrow through an unprotected pointer
cannot make an already freed Object safe. With concurrent callers,
accepting a new borrow and closing admission to borrows during
retirement must be synchronised. The Class’s contract states how the
owner supplies a live reference, which operations a borrow permits, and
which resources remain available after retirement.
A borrow protects lifetime; it does not by itself grant permission to mutate private state or make concurrent method calls safe. Those remain separate Object and synchronisation contracts. A counter may implement borrow tracking, but the counter is private machinery, not the ownership model.
_destroy retires the Object atomically with respect to
borrow admission. An outstanding borrower may finish its work and
release; it cannot acquire a new borrow after retirement. An existing
borrow may be handed onward as an explicit transfer of its release
obligation, without registering a new borrow. The final release performs
reclamation on its calling thread; no waiting thread or thread per
retired Object is needed. An Object retained by a borrower which never
releases keeps its resources: freeing something that may still be used
would violate the purpose of borrowing.
A borrow protects the resources the borrower relies on, not merely the Object’s allocation. Owned resources on which outstanding borrowers rely must survive until final reclamation; other owned resources may be released during retirement. Borrowed parents must either outlive every operation by the documented hierarchy, or be protected separately. Do not introduce cycles of tracked borrows. Removing an Object from a shared registry precedes retirement, and establishing a borrow happens while that registry still protects the pointer. Neither a Class tag nor an atomic counter can rescue an already stale pointer.
Logical shutdown and memory lifetime are distinct responsibilities.
Stopping an owned worker or withdrawing an authority may still require
coordination; it must not be disguised as waiting in
_destroy for unrelated borrowers.
Once this pattern is understood, unfamiliar functions become easy to
classify: mwsd_handshake_process advances the Handshake’s
state machine; mwsd_channel_run is the Channel’s
long-running thread loop; mwsc_projector_run is the
Projector’s GUI and render loop.
3.12 Public vs. private methods
Mercurius Classes are implemented in C, so “public” and “private” are expressed using linkage rather than language keywords. Both follow the same naming, method-shape and error-handling rules; their distinction is whether they form part of the Class’s published interface.
Public methods form part of the Class’s interface. They are declared in its header and have external linkage.
Private methods are implementation details of a single translation unit. They must be declared
static, so they have internal linkage and cannot be named from outside the implementing.cfile. A nanoclass and its methods normally live here (§3.6).
static controls who can name a method, not who can reach
it. A private method may still be reached through an interface its Class
deliberately publishes, as a concrete Transport’s operations are reached
through Transport’s operations table. Only the Class decides what it
exposes.
This keeps each Class’s public surface small and explicit (§3.5), and ensures that helper functions cannot accidentally become part of the external API.
4. Applying the model to Mercurius
The rules above are a general engineering discipline. Mercurius supplies a substantial worked example of that discipline in use.
4.1 Presence, not pixels
Mercurius begins from a simple belief:
A workstation is a presence, not a device. You should be able to inhabit it from anywhere.
The Workstation is the long-lived centre of gravity. It owns authoritative Session state and the resources which make that state useful. A Portal is an authenticated access point which supplies display and input; it is not the authority for the user’s work. Local access is another Portal rather than a separate model of the system.
This philosophy creates an unusually clear test for object boundaries. Sessions must outlive connections. A transient network object must not own a user’s long-lived state. A Portal must not acquire authority merely because it presents a Window. Routing input and rendering output must preserve the identity of the association, Session, and Window to which they belong.
Those requirements do not prescribe one large procedure. They call for objects whose ownership, authority, and Messages express the required relationships directly.
4.2 A community of cooperating objects
Mercurius contains objects named Transport, Controller, Broker,
Session, Application, Channel, Compositor, Presenter, and Projector.
Their complete runtime arrangement is documented in
Architecture.md; what matters here is how they illustrate
this model.
A Transport owns transport mechanics, not Session policy. A Controller understands the control-plane Messages for which it is responsible and routes other Messages onwards. A Broker owns Sessions and decides which Controller may attach to them. A Session remains authoritative for its own Applications and Windows. A Compositor, Presenter, and Projector collaborate to make a Window visible without collapsing into one rendering procedure.
No object needs to understand the whole path. Each knows its neighbours, its own state, and the Messages it is entitled to interpret. The system’s behaviour appears only when those objects run together.
This is the important distinction between an object community and a collection of structures with functions attached. The names and method shapes make objects visible in C; the limited knowledge and Message-driven collaboration make them objects in the architectural sense.
4.3 Ownership makes persistence possible
The Iron rules turn the philosophy of long-lived presence into a lifetime structure. The Broker owns Sessions; a Controller may borrow an attached Session but cannot destroy it. A Controller or Transport may disappear while the Broker and Session remain. Detachment is therefore a change in a relationship, not a migration of ownership or a reconstruction of the user’s state.
The same rule applies throughout the system: the longer-lived authority owns the shorter-lived state, while transient collaborators borrow only what they need. Teardown follows the ownership graph, and loss of one edge does not silently confer ownership on another object.
This is more than memory management. Ownership determines who may decide, which failures are local, and which state survives the loss of a collaborator.
4.4 Security emerges from legitimate routes
Mercurius Messages have universally understood headers and payloads which belong only to their semantic sender and receiver. The Message type and the object path together provide the context needed to route and authorise the Message. Intermediate objects may obtain the routing information for which they are responsible; they do not thereby acquire the right to interpret or mutate the semantic payload.
That rule preserves security even for internal Messages. An
MWS_RENDER_UPLOAD enters through a Channel owned by an
Application belonging to exactly one Session. The Session resolves the
Window identifier only within its own Window collection, so sharing a
process does not give Eve or Mallory a route to Alice’s or Bob’s
Window.
A detached Session has no current Portal association, but retains its identity, ownership graph, and authority. Suspending or resuming its Applications is Session lifecycle policy; it does not supply the security boundary. If a Message is subsequently sent to a Portal, the Session uses its current Controller and association binding.
The object graph does not replace authentication, validation, or cryptography. It ensures that successful authentication does not lead into a program full of global tables and convenient cross-object functions which must each recreate the same authority checks. Legitimate references and Messages are supplied along legitimate relationships; crossing a security boundary consequently requires breaking a visible object-model invariant.
4.5 Zero to many
Mercurius treats absence and multiplicity as ordinary. There may be zero, one, or many Transports, Controllers, Sessions, Applications, Channels, GPUs, Compositors, Presenters, Projectors, Windows, and Portals. The implementation discovers or creates objects as needed and reports a resource failure only when it genuinely cannot satisfy a request.
This is another consequence of object identity and explicit ownership. No component depends on a global current Session, current Window, or only GPU. Each instance carries its own state and participates in the same relationships as every other instance. Code written for one object therefore remains structurally correct when a second appears.
5. What the Mercurius example demonstrates
Mercurius is not included here as a catalogue of Classes. It is evidence that the discipline can organise a concurrent systems program with long-lived and short-lived state, local and network delivery, multiple authentication mechanisms, several resource domains, and security-sensitive routing.
The example supports several general claims:
- Message passing limits knowledge. A sender can state what happened without discovering the eventual receiver or its location.
- Ownership gives lifetime and authority one visible structure. The object which creates and owns state is also the natural place to govern it.
- Opaque payloads prevent incidental coupling. Carrying a Message does not entitle an intermediate object to understand the exchange.
- Standard interfaces make unfamiliar Classes legible. Lifecycle, Message handling, state-machine progress, and long-running behaviour have recognisable shapes.
- Multiplicity exposes hidden assumptions. A design which works only with a singleton is forced to reveal that limitation rather than hiding it in global state.
- Security can be structural. The absence of an illegitimate route is stronger and easier to review than a distant procedure which can reach everything and promises to check first.
These properties do not arise from the C syntax. They arise because the running program has been designed as cooperating objects and because the Iron Rules are treated as load-bearing constraints.
For the complete Mercurius object graph, startup order, concrete
ownership relationships, and individual component responsibilities, see
Architecture.md.
6. Applicability beyond Mercurius
Mercurius is one application of this object model, not the definition of its limits. The model is useful wherever a system is easier to understand as a community of independent objects than as a sequence of procedures operating on shared state.
The essential pattern is small:
- Every object has identity, a single responsibility, and an explicit owner.
- Ownership and borrowing are visible and never change silently.
- Every Class has a predictable lifecycle and behavioural interface.
- Objects collaborate primarily by constructing and sending Messages.
- A Message is interpreted only by the objects entitled to understand it; intermediate objects route it without acquiring its authority.
- Domain-specific methods exist where they express an honest local operation, but they are not the first resort for collaboration.
- Collections are dynamic and absence and multiplicity are normal: 0..many, rather than a singleton made global for convenience.
None of these ideas depends on windows, graphics, SCTP, Vulkan, or any other Mercurius-specific concern. They describe how to divide responsibility and preserve boundaries in a long-lived software system.
6.1 Why Message passing matters
Ordinary procedural decomposition answers the question, “Which function performs this step?” Message-oriented design first asks, “Which object has the authority and responsibility to receive this request?” That difference remains important even when both implementations ultimately execute a C function.
An explicit Message makes the collaboration itself visible. It records what happened, who initiated it, and what kind of object should consume it. The sender need not discover the receiver’s implementation or manipulate its state. Intermediaries can route the Message without learning its semantic payload. A receiver can change its implementation without requiring every sender and router to change with it.
This produces loose coupling of knowledge, not an absence of cooperation. Objects may collaborate closely and their Message formats may deliberately evolve together. The boundary is that unrelated objects do not become coupled to that exchange merely because they carry it.
Message passing is also independent of physical topology. A Message may stay inside one translation unit, cross a thread boundary, travel between processes, or be encoded on a network. Moving the receiver should change the delivery mechanism, not force the sender to learn a different model of the system.
6.2 What the Iron rules contribute
Message passing alone does not define lifetime. In a garbage-collected Smalltalk image, the runtime carries much of that burden. In C, ownership must be made explicit by design.
The Iron rules give each object one place in an acyclic ownership
graph. An owner knows what it must destroy; a borrower knows what it
must not destroy; and a short-lived collaborator cannot silently take
control of a longer-lived object. The standard _create and
_destroy interface makes that graph executable during both
normal shutdown and partial failure. Where borrowing needs explicit
tracking, _borrow and _release make its
lifetime equally visible while leaving destruction with the owner.
This has consequences beyond memory management:
- Authority has a location. A decision belongs to the object whose responsibility and knowledge justify making it.
- Failure remains local. An object reports the facts it owns and returns control rather than choosing recovery on behalf of its caller.
- Teardown is intelligible. Destruction follows ownership instead of a collection of unrelated cleanup calls.
- Multiplicity is tractable. Each instance carries its own state, so adding another object does not require another global “current” variable.
- Security boundaries can become structural. References and Messages can be provided only along legitimate relationships, reducing the number of places which must recreate authority with ad-hoc checks.
The rules do not magically prevent every leak, race, denial of service, or authorisation defect. C still permits mistakes, and validation is still required at every untrusted boundary. Their value is that ownership, authority, and collaboration are made explicit enough to inspect, test, and reason about.
6.3 Where the model is useful
The approach is most useful when software has several of these properties:
- many concurrent instances of the same conceptual thing;
- long-lived state mixed with short-lived requests or connections;
- resources whose ownership and destruction matter;
- events that cross threads, processes, devices, or networks;
- security decisions that must remain with a particular authority;
- implementations expected to outlive today’s hardware and topology;
- several interchangeable backends behind one stable role.
Examples include network services, storage systems, device managers, GUI toolkits, game engines, embedded controllers, protocol implementations, and distributed applications. In each case the nouns differ, but the questions remain the same: Who owns this object? Who may send it a Message? Which object is entitled to act? Who destroys it? What happens when there are zero, one, or many?
The model has a cost. It requires discipline, more deliberate naming, and a willingness to resist convenient calls which bypass the object graph. A small calculation with no identity, lifetime, or collaboration does not become better merely by being wrapped in a Class. The purpose is not to turn every function into an object; it is to keep systems made of real objects from degenerating into shared state and procedural reach-through.
6.4 A review test
When adding behaviour to a system built this way, ask:
- Which object has the responsibility and authority for this behaviour?
- Is this an intrinsic local operation, or should it be expressed as a Message?
- Who is the semantic sender, and which Class is entitled to consume the payload?
- Are intermediate objects routing the Message, or have they begun to interpret an exchange that does not belong to them?
- Does a new domain-specific method clarify a real boundary, or bypass one for convenience?
- If a method orchestrates several steps, does that complete operation belong to the object, with every delegated step and cleanup path remaining inside its authority?
- Is every reference owned or explicitly borrowed, and is any transfer of ownership unmistakable?
- Where borrows are tracked, is each successful _borrow matched by _release, and do outstanding borrows preserve every resource they need after ownership ends?
- Can every public method reject invalid arguments or an invalid lifecycle state without crashing or damaging the object?
- Can the owner destroy the object and every resource it owns after full, partial, or failed construction?
- Does the design still make sense with zero, one, or many instances and no implicit “current” object?
If those questions have clear answers, the design is likely preserving the model. If the answers require global state, knowledge of a distant object’s internals, or a special case for the second instance, the design has probably started to become a bucket of C.
6.5 Intellectual lineage and language independence
Mercurius is implemented in C because C is the language in which its author can express systems ideas fluently and because every computer of interest has a C compiler. The architectural model belongs to no language.
This discipline makes no claim to have invented object collaboration, contractual interfaces, or explicit ownership. Its primary influence is Smalltalk’s message-oriented object model. It also draws from Design by Contract, described by Bertrand Meyer in Object-Oriented Software Construction and embodied in Eiffel; established C systems practice; and the ownership vocabulary later made familiar by Rust. Picasso would be proud.
What is offered here is the synthesis: an explicit account of how its author believes software should be designed when given the time and space to do so. Smalltalk supplies the central idea of software as cooperating objects sending Messages, with behaviour emerging from their collaboration at run time. Design by Contract informs the explicit obligations and invariants of every method. C requires ownership and dispatch to be expressed through convention and ordinary data structures, while Rust supplies a useful modern reference point for several of the ownership and lifetime goals. Mercurius provides a substantial contemporary example.
Other languages can enforce different parts of the same model directly:
- Rust can encode much of the ownership and borrowing graph in its type system.
- Eiffel can state method preconditions, postconditions, and object invariants as executable contracts.
- Actor languages can provide isolation and Message delivery as runtime primitives.
- Object-oriented languages can supply identity and dispatch while leaving authority and ownership to the design.
The syntax and enforcement mechanisms change; the architectural questions do not. A successful implementation in another language would preserve the same independent responsibilities, Message boundaries, ownership relationships, and deliberately small behavioural interfaces rather than reproduce the surface appearance of the C code.
This is therefore not the claim that “object-oriented” means the implementation should have been written in C++ or Rust. Those languages may be suitable implementation media, but choosing one does not create this architecture. A C++ hierarchy can still become a procedural system hidden behind methods, and a Rust program can have impeccable memory ownership while assigning behaviour and authority poorly. Conversely, plain C can express the model faithfully when its object and Message boundaries are treated as load-bearing design.
That is the broader lesson of Smalltalk-style software design in C:
Design in Smalltalk. Implement in the language appropriate to the system.
Footnotes
Alice and Bob conventionally represent legitimate participants in security examples. Eve represents an eavesdropper; Mallory represents an active attacker who may forge, alter or inject communications.↩︎