Information Hiding: Give Each Design Decision a Clear Owner

Changing a preference from darkMode: true to theme: 'dark' looks like a rename. It becomes a compatibility problem as soon as an existing user opens the application with an old saved document.

In the illustrative application below, preferences are stored as JSON. The UI needs a theme and a display density; saved documents may come from different application versions. The reader, writer, and migration code all need to agree about what those documents mean.

Suppose those activities live in separate modules, each with its own format rules. A representation change now reaches all three. A settings component that constructs JSON directly adds another place to coordinate. Small files and private fields have not given the format a clear owner.

Information hiding addresses this kind of dependency by organizing code around a decision and the knowledge required to implement it. Encoding and decoding happen at different times, but they can belong to one owner because they describe the same representation.

This article builds a TypeScript preferences codec that reads two versions and exposes one current application type. We will also examine the boundary it must leave visible: an unsupported document is a reason to choose a recovery policy, not permission to overwrite the user's data.

On this page

Private Members Can Still Expose a Decision

Consider a class with a private JSON string and public accessors for its raw value. The language prevents direct access to the field, but callers still need to understand the format to do anything useful with it.

Moving the string behind a getter has restricted access without hiding the representation's meaning.

The same problem appears without classes. Two modules can have no exported constants in common and still independently depend on the same field names, version markers, or encodings. A format change requires coordinated edits even though the dependency does not appear in an import graph.

This is information leakage: a design decision is reflected in multiple places. The problem is especially hard to see when modules appear independent at their formal interfaces but carry matching assumptions internally.

A better diagnostic is to propose a change to one decision. If the persisted field darkMode becomes a theme value, which code must understand that transition? Every required edit reveals an owner of the representation, whether or not a private keyword appears anywhere.

Define the Application's Meaning Separately From Its Representation

Suppose the current application needs two preferences:

export type Preferences = {
  theme: 'light' | 'dark'
  density: 'comfortable' | 'compact'
}

That type expresses information the application legitimately uses. A settings control must know which themes exist. A layout needs to know whether compact presentation is requested.

The persisted representation can have its own history. An earlier version might contain:

{ "v": 1, "darkMode": true, "compact": false }

The current version might contain:

{ "v": 2, "theme": "dark", "density": "comfortable" }

Both describe the same preferences. A component displaying a dark, comfortable layout does not need to know which representation produced them.

The design decision to hide is the serialization and compatibility mechanism: field names in storage, version dispatch, validation of stored values, and translation into current application meaning.

This boundary does not hide the preferences themselves. Hiding information that consumers need would only make them guess or reach around the interface.

Put Both Directions of the Format in One Owner

A preferences codec can own encoding and decoding even though those operations happen at different times.

Its public result should communicate whether the stored value could be interpreted, without requiring the caller to inspect individual wire fields:

export type DecodeResult =
  | { ok: true; value: Preferences }
  | {
      ok: false
      reason: 'invalid-json' | 'unsupported-version' | 'invalid-shape'
    }

Here is a small implementation. The exported functions and types belong to one codec module; helper functions remain internal.

function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === 'object' && value !== null && !Array.isArray(value)
}

export function decodePreferences(text: string): DecodeResult {
  let value: unknown

  try {
    value = JSON.parse(text)
  } catch {
    return { ok: false, reason: 'invalid-json' }
  }

  if (!isRecord(value)) {
    return { ok: false, reason: 'invalid-shape' }
  }

  if (value.v === 1) {
    if (
      typeof value.darkMode !== 'boolean' ||
      typeof value.compact !== 'boolean'
    ) {
      return { ok: false, reason: 'invalid-shape' }
    }

    return {
      ok: true,
      value: {
        theme: value.darkMode ? 'dark' : 'light',
        density: value.compact ? 'compact' : 'comfortable',
      },
    }
  }

  if (value.v === 2) {
    if (
      (value.theme !== 'light' && value.theme !== 'dark') ||
      (value.density !== 'comfortable' && value.density !== 'compact')
    ) {
      return { ok: false, reason: 'invalid-shape' }
    }

    return {
      ok: true,
      value: { theme: value.theme, density: value.density },
    }
  }

  if (typeof value.v !== 'number') {
    return { ok: false, reason: 'invalid-shape' }
  }

  return { ok: false, reason: 'unsupported-version' }
}

export function encodePreferences(value: Preferences): string {
  return JSON.stringify({
    v: 2,
    theme: value.theme,
    density: value.density,
  })
}

The decoder validates runtime data instead of asserting that parsed JSON has the TypeScript type it wants. It accepts supported old representations, normalizes them, and distinguishes an unsupported version from malformed data.

The encoder writes the current representation. It assumes its input has already satisfied the application-level Preferences contract; TypeScript types do not validate untrusted inputs at runtime.

Neither operation chooses where bytes are stored, which user owns them, or when they should be saved. Those are separate decisions with separate reasons to change.

Execution Order Still Exists

Return to the settings interaction. The application still reads stored text, decodes it, updates a preference, encodes the result, and saves it. The runtime sequence has not changed. What changed is where a maintainer must understand the representation.

For example, a storage adapter can provide strings without interpreting their contents, while an interaction handler works with Preferences. The codec participates during both reading and writing.

This is the problem with temporal decomposition. Runtime stages are an attractive organizational guide because engineers encounter them in order. But when the same decision affects several stages, placing each stage in a different module can distribute that decision throughout the system.

Separate stages can still be appropriate when they depend on different knowledge. Transporting bytes and interpreting a versioned preferences format need not belong to the same component. The criterion is what must be understood together, not whether two operations happen consecutively.

Likewise, putting encoding and decoding in one file is insufficient if callers keep assembling JSON objects, examining v, or translating old boolean fields. The intended ownership has to be reflected in actual use.

Let the Application Own Recovery Policy

Now open a version-three document with an older application. The decoder correctly reports an unsupported version. The user still needs an interface they can understand, and the original document still contains information this application cannot interpret.

An application might show a warning, temporarily use a default in memory, ask for a reset, or require an update. The choice depends on whether losing preferences is acceptable and whether another application version may have written them.

Keeping that decision visible is especially important for writes. A fallback that silently replaces an unknown document with current defaults can destroy data written by a newer version. Returning unsupported-version gives the application a way to avoid that overwrite.

Similarly, the codec should not automatically save a normalized version-two document while merely decoding version one. Reading and rewriting have different side effects. An application can choose to migrate after a successful read, but it must consider permission to write, concurrent updates, storage failures, and older readers.

The codec owns how the bytes represent preferences. The application owns whether a particular interaction should change persisted state. Clear ownership on both sides makes information hiding useful without turning the module into an authority over unrelated behavior.

Compatibility Is Still a Contract

Owning a representation does not make every representation change safe.

An older deployment may still read the same storage. Multiple tabs may run different application versions. A server and a browser may be upgraded at different times. A migration may need to preserve fields that the current application does not understand.

The example codec intentionally supports a narrow policy: read versions one and two, normalize known fields, and write version two. It does not preserve unknown extension fields when decoding and re-encoding. That limitation is acceptable only if the actual format contract permits it.

Before introducing a new version, establish which readers must remain compatible, how long old representations remain supported, and whether old writers could erase new information. Those are deployment and data-lifecycle requirements; a neat module boundary cannot decide them by itself.

The boundary still helps. Compatibility decisions have one format owner to implement and test, and consumers can continue using the application representation when its meaning is unchanged.

Test the Decision at Its Owner

Tests for this codec should exercise the representation knowledge it owns:

  • Version-one combinations normalize to the correct theme and density.
  • Valid version-two data returns the current preferences.
  • Malformed JSON and wrong field types fail explicitly.
  • Unknown versions remain distinguishable from valid preferences.
  • Encoding emits the supported current version.
  • Decoding an encoded valid preference preserves its application meaning.

The last property is a semantic round trip, not a promise to reproduce the original bytes. A version-one document becomes version two when deliberately re-encoded, and JSON formatting may change.

Consumers can test behavior using Preferences and public decode outcomes. They should not duplicate version dispatch just to construct ordinary settings scenarios. Format-specific fixture builders belong with the codec tests, where their knowledge is intentional.

This arrangement makes a future field-representation change reviewable. A reviewer can inspect the codec and its compatibility cases, then verify whether application meaning or recovery policy also changes.

Follow the Decision When Reviewing a Boundary

For an existing module, choose a concrete representation or algorithmic decision and ask where it is understood. Search beyond exported fields: tests, migration scripts, background jobs, and convenience code can all encode the same knowledge.

Then separate the facts that consumers need from the mechanism they should be able to ignore. In this example, consumers need theme and density, plus meaningful failure outcomes. They do not need to know that version one represented those preferences with booleans.

For these preferences, put version dispatch, field validation, normalization, and encoding in the codec. Let UI code use theme and density. Make an unsupported version an explicit outcome, and require a separate application decision before writing anything over it.

The next time the JSON shape changes, the format owner should implement that change. The settings screen should change when the user's choices or required behavior change. That separation gives information hiding a result you can inspect in a real feature.