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);
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);
value: 1
privateCounter: undefined
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())
value: 0
value: 2
value: 1
- Verdict: native. Each
.pyfile is a module with its own namespace, so the usual form is a filecounter.pywith 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";
}
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
exportfor the same purpose.
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());
}
}
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()}");
}
}
value: 0
value: 2
value: 1
- Verdict: idiom. A
static classcannot have instances, so it acts as a module. Namespaces group names but have no private members;internallimits a name to its assembly.
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());
value: 0
value: 2
value: 1
- Verdict: idiom. The IIFE is the classic form. In code that uses ES modules, a file with
let privateCounterandexport function increment()gives the same privacy with no wrapper.
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());
value: 0
value: 2
value: 1
- Verdict: idiom. The
Counterinterface is the public API, and the compiler rejectscounter.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())
}
value: 0
value: 2
value: 1
- Verdict: native. The Go form is a package
counterwith an unexported variableprivateCounterand exported functionsIncrement,DecrementandValue; a name is exported only if it starts with an upper-case letter. The closure here keeps the example in one file.
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());
}
value: 0
value: 2
value: 1
- Verdict: native. A
modblock is a module, its items are private by default, andpubmakes the API.counter::change_by(1)inmaindoes 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.
Variants and related patterns
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
- Module pattern, Wikipedia, Introduction; Features; Comparisons to other concepts
- JavaScript modules, MDN Web Docs, A background on modules; Other differences between modules and classic scripts; Exporting module features
- Closures, MDN Web Docs, Emulating private methods with closures
- The Python Tutorial, Modules, Python 3.14, 6.1 More on Modules
- The Go Programming Language Specification, Exported identifiers
- The Rust Programming Language, Control Scope and Privacy with Modules, Modules Cheat Sheet; introduction
- ECMAScript 2015 Language Specification, ECMA-262 6th Edition, title page (6th Edition, June 2015); 15.2 Modules
- Modules, CommonJS modules, Node.js v24 documentation, The module wrapper
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag Q1310M Edit this page History Report an error Markdown