Skip to main content

Revealing Module Pattern

Define all functions privately, then reveal selected ones publicly

Pattern Overview

🎭 Revealing Module Pattern

The Revealing Module Pattern is a variation of the Module Pattern where all functions and variables are defined privately, and then a public API is created by revealing selected private functions through the return statement.

Core Concepts

🔹 Private by Default - All functions defined as private within IIFE
🔹 Selective Exposure - Choose which functions to make public
🔹 Clean API - Return object clearly shows public interface
🔹 Consistent Access - Private functions can call each other directly

Key Differences from Classic Module Pattern

Classic Module: Functions defined directly in return object Revealing Module: All functions defined privately, then revealed Advantage: Cleaner separation between public and private Advantage: Consistent calling convention for private functions

Real-World Applications

API Clients - HTTP methods private, expose selected endpoints Calculators - Math operations private, reveal chosen functionality Event Systems - Internal event handling private, expose listener API Configuration Managers - Internal validation private, expose settings API

Pattern Benefits

Clear Intent - Public API explicitly defined in return statement Better Organization - All function definitions together, then public mapping Easier Refactoring - Can easily change what's public without moving code Consistent Naming - Private functions keep their names when revealed

Implementation Benefits

Explicit public API - Clear separation between public and private
Better readability - Public interface visible at end of module
Flexible exposure - Easy to change what's public/private
Consistent internal calls - Private functions call each other directly

Examples:
Perform mathematical operations with private validation and public calculation methods
Input:
calc.add(10).multiply(5).getCurrentResult()
Output:
50
HTTP client with private helper functions and public resource-specific methods
Input:
api.setApiKey("key"); api.users.getById(1)
Output:
User: John Doe
Event system with private validation functions and public listener management
Input:
emitter.on("test", handler); emitter.emit("test", "data")
Output:
Handler: data

Concepts

design patternssoftware architecturecode organizationobject-oriented programming

Complexity Analysis

Time:O(1)
Space:O(n)

Implementation

calculator-module

Time: O(1) | Space: O(n)
const CalculatorModule = (function() {
  let result = 0;
  const history: string[] = [];
  
  function add(value: number): number {
    result += value;
    history.push(`+ ${value}`);
    return result;
  }
  
  const getCurrentResult = (): number => {
    return result;
  };
  
  return { add, getCurrentResult };
})();