By way of background, I recently coded a small app that detects the number of boxes in an image. The app defines some types, for example:

class Box(val x1: Int, val y1: Int, val x2: Int, val y2: Int)

This app is Kotlin, but the principles should apply to any strongly-typed language. The definition of Box above is how I've typically seen code written. It works just fine. However, just using Int for the type, we could inadvertently assign an X-coordinate, where Y-coordinate is expected. I realised I could use the type system to avoid such an error, by defining XCoordinate and YCoordinate types:

class Box(val x1: XCoordinate, val y1: YCoordinate, 
          val x2: XCoordinate, val y2: YCoordinate)

In fact, when I did this I actually detected a bug - I'd copy&pasted code to detect horizontal lines to detect vertical lines, and forgotten to update one bit.

I figure this is not a novel technique, but I've not really come across it in practice, and without knowing what it's called, it's hard to Google. If you have information on what the technique is called, or even better, advice on how to do it well, that would be great!


1 Answer 1


I've seen it called the Tiny Types Pattern, but many (especially people coming from the world of statically-typed functional languages) would simply call it "good design".

The CHECKS Pattern Language has the Whole Value Pattern, which is an extension of this idea. Of course, one could also argue that this is just domain modeling.

A specific instance of the "opposite" would be the Primitive Obsession Code Smell. A specific case of abuse of primitives is Stringly Typed code.

Many statically typed functional languages have a specific feature for this, e.g. in Haskell, it is called newtype. A newtype is almost like an alias of an existing type, BUT it is treated as a distinct type by the type checker. It has zero overhead, since it is erased to the original type (or rather it is erased to the same type as the original type).

  • Thanks for this. Yes, that's exactly it, and I agree that it's good design. I don't really work with functional languages, but can't remember ever seeing in a commercial or open-source code base.
    – paj28
    Feb 22, 2020 at 17:57
  • Languages like Haskell have a specific feature for this: newtype creates an "almost-alias" for an existing type, that behaves like an alias except for one thing: it is considered to be a distinct type. This is unlike a typedef in C, which only creates an additional name for a type, but if I have a typedef int xCoordinate and a typedef int yCoordinate, I can still pass an int, because I haven't created a distinct type. Feb 22, 2020 at 18:05
  • also seen type driven design/development
    – jk.
    Apr 27, 2021 at 8:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.