Programming Search⌘K

Patterncore

Module pattern

Also called JavaScript module pattern, IIFE module, module object.

The module pattern groups private state and a public API in one closure or object, in a language without full support for modules. It was the usual form of a JavaScript module before ES modules.

Family
structural-design
Intent
Give a language with incomplete support for modules the features of a module: one named unit with a public API, and private state and helpers that code outside the unit cannot reach.
Also called
Module

Intent

Give a language with incomplete support for modules the features of a module.1 The unit has one name and a public API. Its state and its helpers are private, and code outside the unit cannot reach them.

Problem

Old browser JavaScript ran every classic script in one global scope. A variable that one script declared at the top level was visible to every later script on the page.2 Two libraries that used the same name changed each other's state, and nothing in the language stopped a caller from changing the internals of a library.

The forces are these:

  • A group of functions shares state, and that state must be private.
  • The group needs one public name, so that it does not fill the global scope.
  • The language has functions or classes, but no module construct with private members.

Here two scripts share the global scope, and the second one changes the state of the first:

This code runs but gives a wrong answer on purpose.

// script 1: a counter
globalThis.count = 0;
function increment() {
  count += 1;
}

// script 2: a list widget that also uses the name count
globalThis.count = 10; // the number of items to show

increment();
increment();
console.log("counter value:", count);
Output
counter value: 12

Solution

Put the state and the helpers inside a function, call the function at once, and return an object that holds only the public functions. The public functions are closures, so they keep access to the private names after the function returns.3

 const counter = (function () {          one scope, created once
     let privateCounter = 0;               private
     function changeBy(n) { ... }          private
     return { increment, decrement, value };   public API
 })();

 caller:  counter.increment()   ok
          counter.privateCounter   undefined

MDN calls this function that is executed as soon as it is defined an IIFE, and says that its closures follow the Module Design Pattern.3 The participants are the scope, which holds the private members, and the API object, which the scope returns.

In other languages, the same pattern uses what the language has. A class with only static members and a private constructor, or a singleton, can stand for a module where namespaces are incomplete.1

Example

The example files show one counter module in each language. It has a private count and a private helper changeBy, and it shows increment, decrement and value. The program prints:

value: 0
value: 2
value: 1
Language Private scope Public API
Python a closure a SimpleNamespace of the closures
JavaScript an IIFE the returned object
TypeScript an IIFE the returned object, typed by an interface
Java a final class with a private constructor static methods
C# a static class public static methods
C++ an unnamed namespace inside a named namespace the functions of the named namespace
Go a closure a struct of functions
Rust a mod block its pub functions

The private name is not on the API object:

const counter = (function () {
  let privateCounter = 0;
  function changeBy(val) {
    privateCounter += val;
  }
  return {
    increment() {
      changeBy(1);
    },
    value() {
      return privateCounter;
    },
  };
})();

counter.increment();
console.log("value:", counter.value());
console.log("privateCounter:", counter.privateCounter);
Output
value: 1
privateCounter: undefined
PythonGitHub
from types import SimpleNamespace


def _make_counter():
    private_counter = 0

    def change_by(val):
        nonlocal private_counter
        private_counter += val

    def increment():
        change_by(1)

    def decrement():
        change_by(-1)

    def value():
        return private_counter

    return SimpleNamespace(increment=increment, decrement=decrement, value=value)


counter = _make_counter()

print("value:", counter.value())
counter.increment()
counter.increment()
print("value:", counter.value())
counter.decrement()
print("value:", counter.value())
Output
value: 0
value: 2
value: 1
  • Verdict: native. Each .py file is a module with its own namespace, so the usual form is a file counter.py with a module-level variable and functions. The closure here keeps the example in one file.
  • A leading underscore marks a name as private by convention; from counter import * does not import names that begin with an underscore.
#include <iostream>

namespace counter {
namespace {  // unnamed: these names are private to this file
int private_counter = 0;
void change_by(int val) { private_counter += val; }
}  // namespace

void increment() { change_by(1); }
void decrement() { change_by(-1); }
int value() { return private_counter; }
}  // namespace counter

int main() {
    std::cout << "value: " << counter::value() << "\n";
    counter::increment();
    counter::increment();
    std::cout << "value: " << counter::value() << "\n";
    counter::decrement();
    std::cout << "value: " << counter::value() << "\n";
}
Output
value: 0
value: 2
value: 1
  • Verdict: idiom. A named namespace gives the module its name, and an unnamed namespace hides the helpers from other translation units. C++20 modules add export for the same purpose.
JavaGitHub
final class Counter {
    private static int privateCounter = 0;

    private Counter() {} // no instances: the class is the module

    private static void changeBy(int val) {
        privateCounter += val;
    }

    static void increment() { changeBy(1); }
    static void decrement() { changeBy(-1); }
    static int value() { return privateCounter; }
}

public class Main {
    public static void main(String[] args) {
        System.out.println("value: " + Counter.value());
        Counter.increment();
        Counter.increment();
        System.out.println("value: " + Counter.value());
        Counter.decrement();
        System.out.println("value: " + Counter.value());
    }
}
Output
value: 0
value: 2
value: 1
  • Verdict: idiom. A final class with a private constructor and only static members stands for a module. Packages and the Java module system control access at a larger scale.
using System;

static class Counter
{
    private static int privateCounter = 0;

    private static void ChangeBy(int val) => privateCounter += val;

    public static void Increment() => ChangeBy(1);
    public static void Decrement() => ChangeBy(-1);
    public static int Value() => privateCounter;
}

class Program
{
    static void Main()
    {
        Console.WriteLine($"value: {Counter.Value()}");
        Counter.Increment();
        Counter.Increment();
        Console.WriteLine($"value: {Counter.Value()}");
        Counter.Decrement();
        Console.WriteLine($"value: {Counter.Value()}");
    }
}
Output
value: 0
value: 2
value: 1
  • Verdict: idiom. A static class cannot have instances, so it acts as a module. Namespaces group names but have no private members; internal limits a name to its assembly.
JavaScriptGitHub
const counter = (function () {
  let privateCounter = 0;
  function changeBy(val) {
    privateCounter += val;
  }
  return {
    increment() {
      changeBy(1);
    },
    decrement() {
      changeBy(-1);
    },
    value() {
      return privateCounter;
    },
  };
})();

console.log("value:", counter.value());
counter.increment();
counter.increment();
console.log("value:", counter.value());
counter.decrement();
console.log("value:", counter.value());
Output
value: 0
value: 2
value: 1
  • Verdict: idiom. The IIFE is the classic form. In code that uses ES modules, a file with let privateCounter and export function increment() gives the same privacy with no wrapper.
TypeScriptGitHub
interface Counter {
  increment(): void;
  decrement(): void;
  value(): number;
}

const counter: Counter = (function (): Counter {
  let privateCounter = 0;
  function changeBy(val: number): void {
    privateCounter += val;
  }
  return {
    increment() {
      changeBy(1);
    },
    decrement() {
      changeBy(-1);
    },
    value() {
      return privateCounter;
    },
  };
})();

console.log("value:", counter.value());
counter.increment();
counter.increment();
console.log("value:", counter.value());
counter.decrement();
console.log("value:", counter.value());
Output
value: 0
value: 2
value: 1
  • Verdict: idiom. The Counter interface is the public API, and the compiler rejects counter.privateCounter. ES modules are the modern form.
package main

import "fmt"

type Counter struct {
	Increment func()
	Decrement func()
	Value     func() int
}

var counter = func() Counter {
	privateCounter := 0
	changeBy := func(val int) { privateCounter += val }
	return Counter{
		Increment: func() { changeBy(1) },
		Decrement: func() { changeBy(-1) },
		Value:     func() int { return privateCounter },
	}
}()

func main() {
	fmt.Println("value:", counter.Value())
	counter.Increment()
	counter.Increment()
	fmt.Println("value:", counter.Value())
	counter.Decrement()
	fmt.Println("value:", counter.Value())
}
Output
value: 0
value: 2
value: 1
  • Verdict: native. The Go form is a package counter with an unexported variable privateCounter and exported functions Increment, Decrement and Value; a name is exported only if it starts with an upper-case letter. The closure here keeps the example in one file.
RustGitHub
mod counter {
    use std::sync::atomic::{AtomicI64, Ordering};

    static PRIVATE_COUNTER: AtomicI64 = AtomicI64::new(0); // private by default

    fn change_by(val: i64) {
        PRIVATE_COUNTER.fetch_add(val, Ordering::SeqCst);
    }

    pub fn increment() {
        change_by(1);
    }

    pub fn decrement() {
        change_by(-1);
    }

    pub fn value() -> i64 {
        PRIVATE_COUNTER.load(Ordering::SeqCst)
    }
}

fn main() {
    println!("value: {}", counter::value());
    counter::increment();
    counter::increment();
    println!("value: {}", counter::value());
    counter::decrement();
    println!("value: {}", counter::value());
}
Output
value: 0
value: 2
value: 1
  • Verdict: native. A mod block is a module, its items are private by default, and pub makes the API. counter::change_by(1) in main does not compile.

Consequences

The benefits are privacy and a clean global scope. The pattern adds one global name, the module, and the private names cannot clash with the names of other scripts. A caller can use only the API, so the module can change its internals.

The costs:

  • One instance. The IIFE runs once, so the module is a singleton. A module that needs many instances must be a factory function, called once for each instance.
  • Hard to test and extend. A test cannot reach the private state, and code outside the module cannot add a method that uses it.
  • No dependency system. The module reads its dependencies from global names, so the order of the scripts on the page matters. The pattern does not load code, and it does not show what a module imports.
  • Memory for each closure. Each public function is a closure. For a singleton this cost is small, but a factory that makes many objects pays it for each object.

When not to use it

Do not use the pattern in a language that has modules. A JavaScript module runs in its own scope, not in the global scope, and its declarations are not visible outside it unless it exports them.2 An ES module gives the privacy of the pattern, with static imports in place of global names. Python has the same feature: each module has its own private namespace, which the functions of the module use as their global namespace.4

Do not use the pattern when the program needs many instances with private state. A class with private fields is clearer.

Built-in modules. Most languages now have the pattern in the language. Wikipedia notes that in Python each .py file is automatically a module.1 An identifier in Go is exported only if it starts with an upper-case letter and is declared in the package block, or is a field or method name.5 In Rust, code within a module is private by default, and pub makes an item public.6 ECMAScript 2015 added modules to JavaScript.7

CommonJS. Node.js puts the pattern in the loader. Before it runs a module, it wraps the code in a function, so that top-level variables are scoped to the module and not to the global object.8

Singleton and facade. The module pattern is often a Singleton pattern, because it makes one instance. Its API can act as a Facade pattern over its private helpers.

Known uses

  • Node.js: lib/internal/modules/cjs/loader.js at v24.0.0 defines wrap, which puts the text (function (exports, require, module, __filename, __dirname) { before the source of each CommonJS module and }); after it. Each module then runs in a function scope of its own.98

References

  1. Module pattern, Wikipedia, Introduction; Features; Comparisons to other concepts
  2. JavaScript modules, MDN Web Docs, A background on modules; Other differences between modules and classic scripts; Exporting module features
  3. Closures, MDN Web Docs, Emulating private methods with closures
  4. The Python Tutorial, Modules, Python 3.14, 6.1 More on Modules
  5. The Go Programming Language Specification, Exported identifiers
  6. The Rust Programming Language, Control Scope and Privacy with Modules, Modules Cheat Sheet; introduction
  7. ECMAScript 2015 Language Specification, ECMA-262 6th Edition, title page (6th Edition, June 2015); 15.2 Modules
  8. Modules, CommonJS modules, Node.js v24 documentation, The module wrapper
  9. Node.js v24.0.0 source, lib/internal/modules/cjs/loader.js, wrap and wrapper, lines 341 to 352

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/Q1310M/text.yaml