Wednesday, October 22, 2008

A serious problem

Hello,
I'm Creighton Hogg and I want to talk to you about typeclass abuse.

Like any form of substance abuse it may seem harmless at first, a way
to recapture the old feelings of modularity you had during your
object-oriented youth; however, you'll quickly find yourself twisting
and obfuscating your code to design the signatures of your typeclass
methods so that they can cover a wide swath of cases that are
fundamentally dissimilar.

Have you noticed signs of:
1. Obsession over reuse of the names of functions?
2. Attempts to use typeclasses to try and treat collections of
dissimilar objects as though they were the same?
3. A frequent need for typeclasses with two or more type
variables?

If so, you may be in grips of typeclass abuse. Please keep the
following in mind as you attempt to deal with your problem.

First, if you want to have a collection of objects that are treated
differently by functions, please consider using an Algebraic Data Type
instead. For more fine grained control over your data types, you may
want to look into GADTs.

Second, if you are needing a number of classes with two or more type
variables, consider that you may be attempting to use a language feature
designed to enable polymorphism to handle extremely specific and
dissimilar cases. You are working against the grain of the language,
and should probably simply accept that you can't overload a function
name to be 20 different functions that each do different things.

Lastly, if you're not actually sure if a typeclass would make your code
more convenient, why not just try writing your code without it? When
you've got a number of use cases down, then maybe you can decide on what
the proper abstraction is.

This message paid for by the Foundation To Get Creighton To Stop Abusing
His Code, a non-profit organization.

3 comments:

Luke Palmer said...

Brilliant! Also, amen, typeclasses are overused.

BMeph said...

Hello, my name is BMeph, and I'm a type-class-a-holic.

Gordon said...

Looking at the "paid for by" line, I see that not only was this post clever, important, and informative, but also self-deprecating! Good work.