Style recommendation for enum as type

I think the central question is do you want the value, i.e. the color of the banana in your example, to be in the type domain or not. What are the implications of being in the type domain?

  • it can be used for dispatch, which in particular means it can sometimes be used more composibly by downstream packages (i.e. you don’t need the “manual dispatch” of a bunch of if-thens to choose what to do based on the value, and other packages can add methods to participate in dispatch)
  • the compiler will try to specialize on the value, compiling separate methods for f(::Yellow) than f(::Brown)
  • if the value is not known at compile time, then calls like f(color::Color) can lead to dynamic dispatch, which is generally slow. Though there are various compiler heuristics like small union splitting (i.e. if it knows that the color is either Yellow or Brown, then it can replace the dynamic dispatch with a faster if-then branch) that can help speed things up in certain cases.

I think putting the value in the type domain is something you need to be fairly conscious of and code around, i.e. ensuring the value is known at compile time for hot loops (e.g. via function barriers), or making use of the specialization to speed things up.

Whereas for a value (not in the type domain), the compiler knows it’s a e.g. ColorEnum but nothing else (except when constant propogration applies), and in particular doesn’t compile specialized functions for each of the various colors and there is no issue with dynamic dispatch.

By the way, I have a blog post about the tradeoffs of putting a value in the type domain (in a different context) that could be helpful.

6 Likes