liveBook · Manning

Newtype idiom

As explained in Functional Design and Architecture: Examples in Haskell

A newtype is a distinct type wrapper around an existing representation that preserves its runtime representation while enforcing compile-time type distinctions.

A newtype wraps an existing representation in a distinct compile-time type. It preserves the underlying value while preventing interchangeable domain values from being passed accidentally. section 5.2.2

Separate names with identical representations

Wrapping both identifiers as strings makes their roles explicit: ControllerName and ComponentIndex remain different to the developer and the compiler, even though each contains a String. section 5.2.2

Use the idiom when:

  • Several parameters share a representation but must not be confused. section 5.2.2
  • A domain-specific language needs safer identifiers than bare strings provide. section 5.2.2
  • Production code should trade a little wrapping for fewer copy-and-paste errors. section 5.2.2

How Functional Design and Architecture: Examples in Haskell covers it

How deep it goes
Defines the wrapper pattern and its compiler-visible distinction, but does not detail construction, unwrapping, or runtime mechanics.
Examples
Uses ControllerName and ComponentIndex as distinct wrappers around String.
What it assumes
Assumes familiarity with typed parameters and bare representations such as String.
What you can do after
Apply it by wrapping bare domain types so the compiler rejects interchangeable identifiers.
How it connects
Connects type safety with embedded domain-specific languages, algebraic data types, and functional programming.

Also explained in

Compare how 4 books explain newtype idiom →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Design and Architecture: Examples in Haskell. The section links point to the parts of the book it draws on.