Skip to content

Use atoms for enumsΒ #312

@pguillory

Description

@pguillory

Currently Enum values are represented by integers in Elixir.

enum Color { RED = 1, GREEN = 2, BLUE = 3 }

struct Pixel {
  1: optional Color color
}
require Color
assert Color.RED == 1
pixel = %Pixel{color: Color.RED}

# Is equivalent to:
pixel = %Pixel{color: 1}

case pixel.color do
  Color.RED -> :ok
end

It seems like it would be nicer if enums were represented by atoms.

pixel = %Pixel{color: :RED}

case pixel.color do
  :RED -> :ok
end

Pros

  1. If you inspect/print a value, it's confusing to see a number and have to go find the thrift definition and map the number back into a name that you can reason about. An atom is directly readable.
> IO.inspect user
%User{status: 7}           # what is that?

...versus...

> IO.inspect user
%User{status: :INACTIVE}   # OK makes sense
  1. Less generated code, faster compile times.

  2. You don't have to require a generated enum module to use the values.

  3. It's more Elixir-y, I think.

Cons

  1. No longer catches invalid enum values. However it didn't catch enums being used in the wrong context, so we need Dialyzer annotations either way for that.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions