On this page

OCaml Abstract Types & Encapsulation Patterns

Published on August 20, 2026

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

Hiding a type's representation behind a module signature is only the mechanism. What that mechanism enables is a deliberate design discipline: arranging a program's types so that invalid data literally cannot be constructed, rather than relying on scattered runtime checks to catch it after the fact. This discipline is often summarized as making illegal states unrepresentable, and it's built from a handful of concrete, combinable patterns, all resting on the same foundation — a type whose representation nothing outside its own module can see or construct directly.

What Abstraction Actually Hides​

Making a type abstract in a signature hides more than just its fields — it hides the type's equation, meaning the fact that it happens to be built from, say, an int or a string underneath. Compare exposing that equation to hiding it:


module type WITH_EQUATION = sig

  type t = int

  val x : t

end



module M : WITH_EQUATION = struct

  type t = int

  let x = 42

end



let a : int = M.x (* fine — M.t is known to equal int *)

module type ABSTRACT = sig

  type t

  val x : t

end



module N : ABSTRACT = struct

  type t = int

  let x = 42

end



let b : int = N.x

(* Error: This expression has type N.t but an expression was expected of type int *)

Once type t appears with no = int attached in the signature, N.t becomes an entirely new type as far as anything outside N is concerned — genuinely incompatible with int, not merely inconvenient to convert. This is the precise mechanism every pattern in this collection builds on: an abstract type gives a module complete, exclusive control over how values of that type come into existence.

Smart Constructors: Validate Once, at the Only Entry Point​

Pairing an abstract type with a single, validating constructor function guarantees that every value of that type satisfies some condition, permanently, for as long as the value exists:


module Percentage : sig

  type t

  val of_float : float -> t option

  val to_float : t -> float

end = struct

  type t = float



  let of_float f = if f >= 0.0 && f <= 100.0 then Some f else None

  let to_float t = t

end

Because Percentage.t is abstract, and of_float is the only function capable of producing one, there is no way for any value of type Percentage.t to exist anywhere in a program without having already passed the 0.0 to 100.0 check. A function that receives a Percentage.t never needs to re-check that range — the type itself is the guarantee, not a comment or a convention asking callers to remember to validate first.

Parse, Don't Validate: Push the Check to the Boundary​

A closely related discipline pushes this idea further: rather than validating a raw value repeatedly, throughout a program, everywhere it happens to be used, convert it into a richer, self-guaranteeing type exactly once, right at the point it enters the system — and let every function afterward rely entirely on that guarantee instead of rechecking it.


module Email : sig

  type t

  val parse : string -> (t, string) result

  val to_string : t -> string

end = struct

  type t = string



  let parse s =

    if String.contains s '@' then Ok s

    else Error (Printf.sprintf "%S is not a valid email address" s)



  let to_string t = t

end

A function that sends a message doesn't take a raw string and re-check it contains @ on every call — it takes an Email.t directly, and by the time any code holds a value of that type, the check has already happened exactly once, at the single point where untrusted input was converted into it. This is the difference between validating (checking a value, but still passing around the same untrusted type afterward) and parsing (converting into a new type that carries the guarantee with it from that point on) — the raw, unchecked string and the validated Email.t are different types, and the compiler won't allow the two to be confused.

Modeling Alternatives as Variants Instead of Optional Flags​

A frequent, subtler source of representable-but-invalid states is reaching for a record with a boolean flag and an optional field, instead of a variant expressing the actual alternatives directly:


type notification_target_unsafe = {

  send_to_all : bool;

  specific_recipient : string option;

}

Nothing about this type prevents { send_to_all = true; specific_recipient = Some "[email protected]" } — both a broadcast and a specific recipient set simultaneously — or { send_to_all = false; specific_recipient = None } — neither one. Both are nonsensical, and both compile without complaint, because the type itself never ruled them out; only careful, disciplined use of the record everywhere it's constructed can prevent them, and that discipline is exactly the kind of thing that erodes as a codebase grows. A variant sidesteps the problem by construction:


type notification_target =

  | All_users

  | Specific_recipient of string

There is no third combination to accidentally produce — All_users and Specific_recipient of string are the only two values this type can ever hold, and any function pattern-matching on it is handling every genuinely possible case, with nothing left to separately validate. This pattern doesn't require an abstract type or a module boundary at all; it's available immediately, just by choosing a variant over a record-with-a-flag whenever a value is really representing a choice between alternatives rather than a bundle of independent fields.

Distinct Wrapper Types to Prevent Mixing Up Primitives​

A function taking two int arguments that mean genuinely different things — a user identifier and a product identifier, say — has no protection against a caller accidentally swapping their order, since both are, as far as the type checker is concerned, simply int. Wrapping each in its own small abstract type closes this gap:


module User_id : sig

  type t

  val of_int : int -> t

  val to_int : t -> int

end = struct

  type t = int [@@unboxed]



  let of_int n = n

  let to_int t = t

end



module Product_id : sig

  type t

  val of_int : int -> t

  val to_int : t -> int

end = struct

  type t = int [@@unboxed]



  let of_int n = n

  let to_int t = t

end

let assign_to_user (uid : User_id.t) (pid : Product_id.t) = ...

assign_to_user can no longer be called with its two arguments accidentally reversed — User_id.t and Product_id.t are entirely distinct types, even though both are represented by a plain int underneath, and the compiler rejects a swapped call outright rather than silently accepting it and producing a subtly wrong result at runtime. The [@@unboxed] attribute on each underlying definition keeps this protection free at runtime: a value of type User_id.t is represented in memory exactly the same way a bare int would be, with the type distinction existing only for the compiler to check, not as an extra layer of indirection or allocation.

Combining These Patterns​

These techniques aren't mutually exclusive — a well-designed module typically layers several of them together. A notification_target might carry a User_id.t inside its Specific_recipient case rather than a bare string; that User_id.t might itself only be constructible through a smart constructor that checks it against a set of known accounts; and the whole notification_target value might only ever be produced through a single parsing function at the boundary where a request first enters the system. Each layer independently narrows what can exist, and together they add up to a type that's considerably harder to misuse than any one pattern applied alone.

Key Takeaways​

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Subtyping & Variance

Next

Phantom Types