Newtypes and Simple Values
Wrapping primitives in types of their own, and giving those types constructors that enforce a rule. Part of Domain modeling with types; how much such a type guarantees is in Strength Of Evidence.
Primitive obsession and the newtype pattern
The Artist excerpts below are from Michał Płachta’s Grokking Functional Programming (PDF, chapter 7), where an artist starts out as primitives only, roughly Artist(name: String, genre: String, origin: String, yearsActiveStart: Int, isActive: Boolean, yearsActiveEnd: Int):
We used primitive types to model the data requirements. As you probably expect, this is far from ideal. However, it’s still a very common practice, and many software architectures are built this way. You are probably aware of some limitations of this approach, but let’s try to list them all.
The book lists five problems (“Problems with the primitive type approach to modeling”). Three are in the Artist type:
- Arguments can be swapped silently.
genreandoriginare bothString, soArtist("Metallica", "U.S.", "Heavy Metal", ...)compiles. To the compiler they are the same type, so it can’t tell which string is which. - Fields depend on each other, and the type doesn’t say how.
yearsActiveEndmeans something only whenisActiveis false. WhenisActiveis true, is it 0? -1? The type allows every combination, so the meaningless ones have to be handled, or documented and hoped about. - The legal values aren’t stated. A genre comes from a small known set, but
Stringalso admits"hevy metal",""or an album title. Every function that branches on genre has to decide what to do with everything else.
Two more are in the signature of the search function that uses it, searchArtists(artists, genres: List[String], locations: List[String], searchByActiveYears: Boolean, activeAfter: Int, activeBefore: Int):
- Primitives carry hidden meanings. An empty
genreslist means “don’t filter by genre”, which nothing in the type says. - Some parameters only make sense together.
activeAfterandactiveBeforeform one period, and both matter only whensearchByActiveYearsis true.
The usual name for this is primitive obsession, a code smell from Fowler’s Refactoring (PDF). An analogy is a form where every field is a free-text box: anyone can fill it in, but the person processing it has to reinterpret every answer.
Other sources describe the same smell from different angles:
- Bloch, Item 62, “Avoid strings where other types are more appropriate”. Strings are poor substitutes for other value types, for enums, for aggregates (several fields joined into one string with a separator) and for capabilities. Item 34 is the same point about the “int enum pattern”,
static final int APPLE_FUJI = 0, where nothing stops you passing an orange where an apple is expected. - Khononov’s connascence (PDF, chapter 6, “Connascence”). Two modules are connascent when a change in one forces a change in the other. Connascence of meaning is agreeing on what a magic value means (status
7); an enumeration turns it into the weaker, compiler-checked connascence of type. Connascence of position is agreeing on argument order, the genre-and-origin swap above. - DDD value objects. Khononov (PDF, chapter 6, “Value object”) refactors a
Personfull of strings and ints (_landlinePhone,_mobilePhone,_email,_heightMetric,_countryCode) intoPhoneNumber,EmailAddress,HeightandCountryCode, moving parsing, unit conversion and domain operations (Color.MixWith) into the types so callers don’t repeat checks or encode units in variable names. Millett and Tune (PDF, chapter 15, “Enhancing Explicitness”) show the same move on an auctionWinningBid: turningint PriceintoPrice(Money)pullsBidIncrementandCanBeExceededByinto one class.
What if I told you that the way we modeled the Artist is the reason why implementing searchArtists was so difficult?
It was difficult because of the second problem and the last two. Before searchArtists could search, its body had to decode what the fields meant together (is this artist active, and which year field applies?) and what its own parameters meant (does an empty list mean “any”?). Move those rules into the types and the search becomes a straightforward filter.
As Płachta notes (“The newtype pattern is ubiquitous”), a newtype wraps an existing type under a new name, usually at no runtime cost, so Location and Genre stop being interchangeable even though both are strings underneath. Every typed language has some version of it:
Haskell newtype Location = Location String
Scala 3 opaque type Location = String
F# type Location = Location of string (single-case union)
Rust struct Location(String);
Kotlin @JvmInline value class Location(val value: String)
TypeScript type Location = string & { readonly __brand: "Location" }On its own, a newtype fixes only the first problem in the list (swapped arguments). A Genre newtype over String still admits "hevy metal"; for that you need a smart constructor or, better, a sum type of the genres. See Strength Of Evidence.
Two cautions:
- Same shape, different meaning. Wlaschin (chapter 5, “Modeling Complex Data”) keeps
ShippingAddressandBillingAddressas separate types even when they have identical fields, because they play different roles and may diverge. - Wrapping can be overdone. King (HTML) is sceptical of wrappers that are wrapped and unwrapped at every use and protect no invariant. Percival and Gregory (PDF, chapter 9) report a similar Python scepticism: applied mindlessly, the cure for primitive obsession adds complexity, and plain primitives in a service’s API keep its clients decoupled from its internal types.
If the wrapper’s cost is a concern, Wlaschin (chapter 5, “Avoiding Performance Issues with Simple Types”) lists three options: a type alias (fast, but no safety), a struct instead of a class, or wrapping a whole collection at once (UnitQuantities of int[]) rather than each element.
Scala: value classes and opaque types
In Scala, the goal is a distinct compile-time type such as UserId that the compiler won’t confuse with another Long, without allocating a wrapper object at run time. Scala 2 offers built-in value classes (class UserId(val value: Long) extends AnyVal), which avoid allocation in direct calls but still box when passed to generic code, stored in arrays or pattern-matched, and the third-party scala-newtype macro library (@newtype), which avoids boxing more often. Scala 3 replaces both with built-in opaque type declarations (opaque type UserId = Long), which are structural aliases inside their defining scope and distinct nominal types outside it, and never allocate.
Opaque types have limits of their own. Wampler (PDF, chapter 9, “Opaque Types and Value Classes”) notes that you can’t override equals or toString for an opaque type, or pattern match on it. Equality also falls through to the underlying type, so a CustomerId and a ProductId that are both Int underneath can be compared with == without complaint. Alexander’s Scala Cookbook (PDF, recipe 23.7, “Creating Meaningful Type Names with Opaque Types”) closes that hole by declaring given CanEqual[CustomerId, CustomerId] = CanEqual.derived and turning on strict equality, so comparing the two becomes a compile error (see Scala Type System). Volpe’s Scala 3 book (PDF, section 4.1.2, “Newtypes”) builds a small Newtype helper over opaque types to auto-derive Eq, Order, Show and JSON codecs, and asks (“Is it worth the trouble?”) whether zero-cost wrappers earn that boilerplate over a one-line case class: avoiding bare primitives matters much more than saving an allocation unless boxing is a measured bottleneck.
Simple values with rules
Wlaschin’s chapter 6 (“The Integrity of Simple Values”) gives the full recipe for a constrained value such as a UnitQuantity between 1 and 1000: a single-case type with a private constructor, a create function that returns a Result, and a value function to read it out. Because the data is immutable, the check happens once and is never repeated. How much that guarantee is worth, and how it can leak, is in Strength Of Evidence.
Units are a special case (“Units of Measure”). F# can attach a unit to a number at no run-time cost, so 5.0<kg> can’t be added to 2.0<m>. Wlaschin also uses units for currencies and for seconds against milliseconds. Other languages get a similar effect from a phantom type parameter, as in Bragilevsky’s Temp unit (PDF, section 11.1.2) or Odersky’s currency case study (Scala Type System).
Library sources
- Wlaschin 2018, Domain Modeling Made Functional – chapter 5, “Modeling Simple Values” and “Avoiding Performance Issues with Simple Types”; chapter 6, “The Integrity of Simple Values”, and units of measure; on Primitive obsession and the newtype pattern and Simple values with rules
- Płachta 2022, Grokking Functional Programming – chapter 7, “Requirements as types”: the source of the Artist excerpts, from primitives to opaque types; on Primitive obsession and the newtype pattern
- Bloch 2018, Effective Java, 3rd Edition – Item 62, “Avoid strings where other types are more appropriate”, and Item 34 on the int enum pattern; on Primitive obsession and the newtype pattern
- Khononov 2025, Balancing Coupling in Software Design – chapter 6, “Connascence”: name, type, meaning and position; on Primitive obsession and the newtype pattern
- Khononov 2021, Learning Domain-Driven Design – chapter 6, “Value object”: primitive obsession in
Personrefactored intoPhoneNumber,EmailAddress,Height(metric and imperial conversions) andCountryCode, andColor.MixWith; on Primitive obsession and the newtype pattern and Simple values with rules - Millett et al. 2015, Patterns, Principles, and Practices of Domain-Driven Design – chapter 15, “Value Objects”, especially “Enhancing Explicitness” (
WinningBidwithint Pricerefactored toPrice(Money)holdingBidIncrementandCanBeExceededBy) andMeterswith unit conversions; on Primitive obsession and the newtype pattern and Simple values with rules - Fowler 2019, Refactoring: Improving the Design of Existing Code, 2nd Edition – the Primitive Obsession smell and the Replace Primitive with Object refactoring; on Primitive obsession and the newtype pattern
- Wampler 2021, Programming Scala, 3rd Edition – chapter 9, “Opaque Types and Value Classes”; on Scala: value classes and opaque types
- Alexander 2021, Scala Cookbook, 2nd Edition – recipe 23.7, opaque types with
CanEqual; on Scala: value classes and opaque types - Volpe 2023, Functional Event-Driven Architecture: Powered by Scala 3 – section 4.1.2, “Newtypes”, and 4.1.2.1, “Is it worth the trouble?”: a
Newtype[A]helper overopaque typederivingEq,Order,Showand codecs, weighed against a one-linecase class; on Scala: value classes and opaque types and the cost of wrappers - Percival et al. 2020, Architecture Patterns with Python – chapter 9, sidebar “From Domain Objects, via Primitive Obsession, to Events as an Interface” (scepticism of mindlessly wrapping primitives, and using primitives to decouple a service layer from domain types before grouping inputs into event dataclasses; see also chapter 5, “Fully Decoupling the Service-Layer Tests from the Domain”, and chapter 1, “More Types for More Type Hints”); on Primitive obsession and the newtype pattern
- Allen et al. 2016, Haskell Programming from First Principles – section 11.9, “newtype”:
GoatsandCowsnewtypes overIntthat can’t be mixed up, no runtime cost, and the difference from type synonyms (only a newtype can have its own instances); on Primitive obsession and the newtype pattern - Skinner 2023, Effective Haskell – chapter 4, section “Creating Type Aliases”:
type Meters = Doubleandtype Seconds = Doublestill letvelocitytake its arguments swapped, so an alias gives “a false sense of safety” and suits only names with the same meaning (String,AppValue = Either AppError); chapter 6, section “Wrapping Types with Newtype”: a newtype is a distinct, zero-cost type that can’t be substituted for what it wraps; on Primitive obsession and the newtype pattern - Maguire 2018, Thinking with Types: Type-Level Programming in Haskell – section 8.1, “Coercions”: Haskell newtypes are guaranteed zero-cost, and
coerceturns[Int]into[Sum Int]without the O(n)fmap Sum; on the cost of wrappers in Primitive obsession and the newtype pattern - Bragilevsky 2021, Haskell in Depth – section 11.1.2, “Delivering information with types”:
newtype Temp unitwith a phantom unit (F against C), on Simple values with rules; section 12.1.2, “The problem of type safety and generalized newtype deriving”:coerceandCoercible, which turn[Int]into[Age]with nomap, and roles (nominal forMapkeys) as the limit, on the cost of wrapping in Primitive obsession and the newtype pattern - King 2020, Names are not type safety – “Other newtype use, abuse, and misuse”: legitimate uses (choosing an instance such as
Sum, rearranging type parameters, hiding a secret key’sShow,DistanceversusDuration) against transparent wrappers such asArgumentNamethat are unwrapped at every use; on Primitive obsession and the newtype pattern
Further reading:
- Hutton 2016, Programming in Haskell, 2nd Edition – section 8.3, “Newtype declarations”: compares
newtype Nat = N Intdirectly againsttype Nat = Int(not a distinct type) anddata Nat = N Int(carries a runtime constructor); on Primitive obsession and the newtype pattern - Kurt 2018, Get Programming with Haskell – lesson 12, section 12.1, “Using type synonyms”, and lesson 14, “Creating types with newtype” (
newtype Name = Name (String, String)when a synonym needs its own type class instance); on Primitive obsession and the newtype pattern