Newtype Pattern, Avoid String Parameter in Strongly-Typed Languages

Page content

Why?

  • String type has generally lots of choices for the values, so it prones to bugs.
  • If your programing language supports strong-typing, you need to consider avoiding Strings as parameters of functions.
  • The trinity, “Good naming (based on DDD) + good typing (struct) + enum”, helps us always.

Newtype patterns in Rust

https://doc.rust-lang.org/book/ch19-03-advanced-traits.html

use std::ops::Add;

struct Millimeters(u32);
struct Meters(u32);

impl Add<Meters> for Millimeters {
    type Output = Millimeters;

    fn add(self, other: Meters) -> Millimeters {
        Millimeters(self.0 + (other.0 * 1000))
    }
}

If we wrote a function with a parameter of type Millimeters, we couldn’t compile a program that accidentally tried to call that function with a value of type Meters or a plain u32. Newtypes are a zero-cost abstraction - there is no runtime overhead.