2

I'd like to hear some pros and cons about where it's best to put Haskell typeclass instances. I identify 2 possible cases and can not decide for myself which one is best:

  1. Put the instances together with the typeclass definition;
  2. Put them together with the types that implement it.

For the sake of this example, lets say we have a ToJSON typeclass. It, as the name says, has a function that converts a to a JSON:

class ToJSON a where
  toJSON :: a -> JSON

Pros for the first case. Putting all ToJSON instances in the actual typeclass file results in a separation of concerns. For example, the Color type should only care about it's constructors and functions that manipulate the color, not about JSON serialization. Let the JSON type worry about that.

Pros for the second case. Assuming we export only Color type and not it's constructors, putting the ToJSON instance in Color.hs allows the use of patters matching. Also, having all of the instances near the type shows the developer all things the type can do.

Keep in mind that this is a personal preference list based on experience. Feel free to add to or disagree about it.

3
  • That is a pretty bad example. The typeclass is defined in the place where JSON is defined. It makes absolutely no sense to take every type that might ever be mapped to JSON and define the instance in that file. That file would then have to be changed every time a new type was added. Jan 24, 2019 at 13:50
  • 2
    Isn't the whole point of typeclasses that instances are independent of the typeclass and the typeclass doesn't know anything about the instances? How can you put all instances together with the typeclass, if you don't even know what the instances are, and in fact, the instances will maybe only be invented in the future? How will you put a typeclass instance in your code for a type that I am only inventing next week? Jan 24, 2019 at 16:52
  • I assume people encounter various use-cases. It would be nice to learn from them, good or bad. Jan 25, 2019 at 20:22

1 Answer 1

2

This best practice is already well known. Typeclassesd instanced at other places have been dubbed Orphan Instances. GHC doesn't like it when you declare orphan instances.

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.