garyb / purescript-codec

General purpose bi-directional codecs
MIT License
16 stars 5 forks source link

Why is `Codec` a type rather than a type class? #14

Open alphashuro opened 3 months ago

alphashuro commented 3 months ago

I have been learning Purescript recently and I have a question if you have some time to entertain me 😅

I was implementing a toy project and before I discovered this package, I created a type class that served as a Codec definition, defining encode and decode functions.

class Codec a b e where
  encode :: a -> b
  decode :: b -> Either e a

I then create an instance of this Codec for each of the types in my domain.

Comparing my implementation to yours, I'm curious about why Codec is implemented as a type in this module rather than a type class?

PS: I know this is probably not the right place for this, let me know if there is a better place to ask such questions.

garyb commented 3 months ago

The short answer is: you can only have one instance for a type when using typeclasses, and the drawbacks of that become apparent quite quickly if you're not in complete control of the serialization format.

I wrote some stuff about it a while back, before these codec-based libraries existed.