apoorv-2204

apoorv-2204

How do you handle enums in your codebase?

The Issue of Enums in Elixir

Elixir doesn’t have a native enum construct, so we usually rely on atoms, strings, or macros to represent named constants.

Observed Issues

String vs Atom:

Some contexts (like pattern matching or internal logic) prefer atoms, while others (like database fields or API responses) require strings.
Maintaining consistency across both can be cumbersome — I eventually prefer enums as strings for simplicity.

Compile-Time vs Runtime Checks:

We can emulate enums using function calls, but not within guards or compile-time contexts.
Macros can provide compile-time validation, but require the require keyword, which reduces simplicity.
There’s no built-in mechanism for enforcing enum constraints at both compile and runtime.

Questions:

How do you handle enums in your codebase?

Do you rely purely on atoms and type specs, or use macro-based libraries for safer compile-time checking?

Would a lightweight, language-level enum-like abstraction make sense for Elixir?

Most Liked

mudasobwa

mudasobwa

Creator of Cure
defmodule MyEnum do
  defmacro sigil_MYENUM({:<<>>, _, [value]}, [] = _modifiers) do
    case __CALLER__.context do
      :match ->
        if value in ~w[one two], do: value, else: raise(value)
      _ ->
        if value in ~w[one two], do: value, else: raise(value)
    end
  end
end

defmodule TestMyEnum do
  import MyEnum

  def test(value) do
    IO.puts(~MYENUM[one])
    IO.puts(~MYENUM[two])

    case value do
      ~MYENUM[one] -> IO.puts("ONE MATCHED")
      ~MYENUM[two] -> IO.puts("TWO MATCHED")
    end

    ~MYENUM[three]
  end
end

This example is a bit overfilled with some shenanigans, but it’d give you a great start.

garrison

garrison

Actually, one thing that does bother me is that there are a few different ways to implement constants and they all have different tradeoffs. I think this is a bit unintuitive.

@my_enum [:first, :second, :third]
def my_enum, do: [:first, :second, :third]
defmacro my_enum, do: [:first, :second, :third]

The third one is the only way to do pattern matching on constants from another module, yet that is the one which is not documented.

garrison

garrison

Of course for database fields Ecto does support enums. For other stuff I generally use atoms and pattern matching. I wouldn’t necessarily be opposed to a native Enum construct but pattern matching and a public constant for enumeration gets you pretty much all of the way there.

I think the type system will help a lot, here (and Dialyzer already helps a bit). I always liked the string literal types in TS. We generally use atoms, but it’s the same idea. Types are most useful for tooling rather than type-checking (i.e. autocomplete).

Last Post!

Asd

Asd

String comparison is linear and is always slower than atom comparison

Use tools which provide specs around APIs and databases. Consider GraphQL API with Absinthe or HTTP API with Oaskit, OpenApiSpex

What do you mean by “compile time checks”? You want to check that some function is always called only with some atoms? Dialyzer does that to some extent, but having stricter compile time checks requires static typing

I find this really funny

Where Next?

Popular in Questions Top

electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New

Other popular topics Top

joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
saif
Hello everyone, Long time lurker first time poster here. I’ve recently begun working on Elixir full-time again! :raised_hands: It’s been...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New

We're in Beta

About us Mission Statement