Type classes are an essential building block for nearly all large Haskell applications. You’ll use them extensively throughout the rest of the book, and they will be common in both library and application code that you encounter. Unlike parametric polymorphism, you should be judicious in your use of type classes. Most large applications and libraries will introduce a few new type classes, but only a few. Overuse of type classes in your application can be a cause of excess abstraction that makes your program more difficult to work with and reason about, rather than easier.

Well-designed type classes should be narrowly focused on a specific feature, and will generally only define a small handful of functions. It’s common to have type classes that only introduce a single new function, and the Natural type class you built in this chapter is fairly close to the natural upper limit for how big most type classes should be. It’s better to introduce a few extra type classes and add dependencies, like making Natural depend on Eq , instead of having a large class.

Here are some good rules of thumb for knowing when to reach for a type class, or when to reach for some other techniques:

  1. If you’re modeling something that exists outside your program, like a real-world object, a mathematical object, or a business process with well-defined operations, then you might want to define a type class.

  2. If your type class would only be used in one or two places, consider passing a function instead of defining a new type class.

  3. If you would only have one instance of your type class, wait to define the class until you need at least one more instance. The “rule of threes” is a good one to follow—consider abstracting the behavior into a type class after the third time you would rewrite code.

  4. If you find that most of your instances are newtype wrappers around some underlying type, then consider using a record that holds functions instead of a type class. In the long run this will be easier to work with, and it more correctly models the API you’ve designed.