Simple Procedural Dependency Injection

By Nikolai Bonderup

Dependency injection means supplying a consumer with an operation or service instead of having the consumer select its implementation internally. Ordinary function parameters can express this directly. When several operations belong together, a struct of function pointers can act as an interface.

The implementation can remain a collection of functions in a module. The application selects an implementation by explicitly mapping the struct's fields to those functions. The consumer calls through the supplied fields, so replacing an implementation means supplying different function pointers.

The examples below use typed pseudocode. fn(...) -> ... describes a function-pointer type, and assigning a function name stores a reference to that function rather than calling it.

A module might implement audio like this:

module DeviceAudio:
    private device

    initialize():
        device = openAudioDevice()

    play(sound: Sound):
        device.play(sound)

    stop():
        device.stop()

Code that deliberately selects this module can call it directly:

DeviceAudio.play(notification)

The module hides its device and implementation details. Its functions are also values the program can pass to other code. That gives the same implementation a second way to be used.

Suppose a notification function needs to play a sound. It can receive that operation as an ordinary parameter:

function notify(sound: Sound, play: fn(Sound) -> void):
    play(sound)

The calling code selects an implementation:

notify(notification, DeviceAudio.play)
notify(notification, BrowserAudio.play)
notify(notification, SilentAudio.play)

Each call supplies a function with the required signature. notify does not need to know which module provides it. The modules need no shared base class, and their functions need not even have the same name. The connection is established by the value passed as the argument.

This is dependency injection. The dependency happens to be represented by a function pointer.

When several operations belong together, the program can collect their function pointers in a struct:

struct AudioAPI:
    play: fn(Sound) -> void
    stop: fn() -> void

The struct describes what a consumer requires. An implementation is selected by explicitly mapping its fields to module functions:

deviceAudio = AudioAPI {
    play = DeviceAudio.play,
    stop = DeviceAudio.stop
}

browserAudio = AudioAPI {
    play = BrowserAudio.play,
    stop = BrowserAudio.stop
}

The fields are ordinary data. deviceAudio.play holds a reference to DeviceAudio.play; browserAudio.play holds a reference to BrowserAudio.play. Nothing requires those modules to declare that they implement AudioAPI. In a statically typed language supporting this representation, the field types let the compiler check that the assigned functions have compatible signatures.

A consumer receives the struct and calls its fields:

function handlePlayback(audio: AudioAPI, command: PlaybackCommand):
    if command.kind == Play:
        audio.play(command.sound)
    else if command.kind == Stop:
        audio.stop()

The same consumer can now be connected to either implementation:

handlePlayback(deviceAudio, playCommand)
handlePlayback(browserAudio, playCommand)

AudioAPI serves the role of an interface: it names a set of available operations and describes how they can be called. The mapping from that interface to an implementation is visible in the struct initialization. Runtime dispatch happens through the stored function pointers.

Many object-oriented implementations provide related behavior through a dispatch table associated with an object. Here, the table of operations is represented explicitly. The exact mechanics depend on the language, but the design purpose is familiar: calling code depends on an operation contract while another part of the program selects its implementation.

The mapping also allows adaptation without changing the original module. Suppose an existing audio library exposes differently named operations:

legacyAudio = AudioAPI {
    play = LegacySound.startSound,
    stop = LegacySound.haltPlayback
}

If their signatures and behavior fit the contract, the mapping is enough. If an operation needs conversion, a small adapter function can do it:

module LegacyAudioAdapter:
    play(sound: Sound):
        LegacySound.startSound(sound.filePath)

legacyAudio = AudioAPI {
    play = LegacyAudioAdapter.play,
    stop = LegacySound.haltPlayback
}

The consumer still uses AudioAPI. The adapter translates between that contract and the existing library's API.

Individual fields can also be selected independently. For example, playback can be logged while stopping still calls the device module directly:

module LoggingAudio:
    play(sound: Sound):
        Log.write("Playing", sound)
        DeviceAudio.play(sound)

loggedAudio = AudioAPI {
    play = LoggingAudio.play,
    stop = DeviceAudio.stop
}

Both operations ultimately control the same device. That behavioral relationship matters: compatible function signatures alone would also allow a table that starts playback on one device and stops another. A function table makes composition explicit, but the programmer must still preserve the contract between its operations.

The same mechanism supports testing. A recording module can supply an operation that stores requests instead of playing sounds:

module RecordingAudio:
    private requested = []

    reset():
        requested.clear()

    play(sound: Sound):
        requested.append(sound)

    requests():
        return copy(requested)

RecordingAudio.reset()
notify(notification, RecordingAudio.play)
assert RecordingAudio.requests() == [notification]

This test uses an ordinary function pointer. The recorder has shared state, so concurrent tests would need separate recording contexts. In a language with closures, a captured local list can provide another solution, provided the receiving parameter accepts a closure-capable callable. A raw function pointer alone does not carry captured variables.

That distinction also matters for module state. Pointing two AudioAPI values at the same module functions does not give them independent devices. If those functions use one private module-level device, both tables use that device. The function table selects behavior; independent state requires an additional mechanism.

One conventional representation pairs function pointers with an opaque context pointer:

struct AudioAPI:
    context: pointer
    play: fn(pointer, Sound) -> void
    stop: fn(pointer) -> void

previewAudio = AudioAPI {
    context = previewDevice,
    play = DeviceAudio.playWithContext,
    stop = DeviceAudio.stopWithContext
}

editorAudio = AudioAPI {
    context = editorDevice,
    play = DeviceAudio.playWithContext,
    stop = DeviceAudio.stopWithContext
}

The caller forwards the context when invoking an operation:

previewAudio.play(previewAudio.context, notification)
editorAudio.play(editorAudio.context, notification)

The implementation functions interpret the context as their own state. The two tables can now use the same functions with different devices. The context must have the expected representation and remain alive for the calls that use it. Typed contexts or closures can express this relationship more safely where the language supports them.

The application can construct these tables where it assembles its subsystems, and pass each consumer the operations it needs. A module does not need to reorganize its implementation around inheritance or declare conformance to every function table that might reference it. Different consumers can build different interfaces from the same functions.

The remaining choices concern the contract and ownership. Operations grouped in one table must behave consistently. Contexts must remain alive while the table uses them. Adding a required operation means updating the places that construct the table. Passing functions instead of objects also does not remove the need to forward dependencies through intermediate code when the architecture requires it.

The mechanism is small: a function parameter for one capability, a struct of function pointers for a group, and an explicit context when state must accompany those operations. These are ordinary functions and data structures performing the work of dependency injection.