alisinabh

alisinabh

Rust-like Enums in Elixir using macros - Good/Bad?

Hi everyone!

My colleagues and I ran into challenges with atoms and tuples in our Elixir codebases, especially when modeling domain states or structured data clearly.
Atoms are handy but also sometimes annoying. They’re global, easy to typo and need extra tests to ensure correctness. Not to mention converting strings safely to atoms isn’t very straightforward (and sometimes unsafe/unreliable even with String.to_existing_atom/1).

I had an idea to solve this and built a PoC library but to be honest I’m not entirely sure if the community would like it. Especially I’m curious to know if you see this in a codebase would it make understanding the code easier or more difficult?

Here is my PoC: (It is called Enuma and is available on Hex.pm if you want to try it out)

defmodule Shape do
  use Enuma

  defenum do
    item :circle, args: [float()]   # Circle with radius
    item :rectangle, args: [float(), float()]  # Rectangle with width and height
    item :triangle
  end
end

circle = Shape.circle(5.0) # = {:circle, 5.0}

require Shape

case shape do
  # Can use them in pattern matching as they are compile time macros
  Shape.circle(r) -> :math.pi() * r * r
  # Above case clause is same as
  # {:circle, r} -> :math.pi() * r * r
  Shape.rectangle(w, h) -> w * h
  Shape.triangle() -> raise "Triangle Area Not Supported!"
end

Generally what Enuma does it generating macros based on the enum definition. It also generates is_* guards that can be used in “when” clauses.

Back to the question

Here’s the thing: Enuma does slightly alter how you’d typically write Elixir code, which might make some developers uncomfortable or lead to mixed styles in codebases.

I’m curious:

  • Do you think libraries like Enuma enhance clarity, or do they risk complicating Elixir’s simplicity?

  • Would Enuma fit well into your projects, or does it feel too different?

  • How do you currently handle structured domain modeling in your code?

  • If you compare it with Ecto.Enum, would you see useful benefits for your usecases?

I’m looking forward to your thoughts!
https://github.com/alisinabh/enuma/

Most Liked

hauleth

hauleth

Good news for you all my fellow alchemists - it is built in:

defmodule Shape do
  import Record

  defrecord :circle, radius: nil
  defrecord :rectangle, width: nil, height: nil
  defrecord :triangle, []
end

circle = Shape.circle(radius: 5.0) # => {:circle, 5.0}

require Shape

case shape do
  # Can use them in pattern matching as they are compile time macros
  Shape.circle(radius: r) -> :math.pi() * r * r
  Shape.rectangle(width: w, height: h) -> w * h
  Shape.triangle() -> raise "Triangle Area Not Supported!"
end
18
Post #2
garrison

garrison

I think this is a problem which is best solved by a type system. TypeScript’s string literal types solve a similar issue. Once you have type inference/checking for atoms the problems you describe should go away.

D4no0

D4no0

I am not sure you should do that to begin with. What is the use-case where you are required to convert strings to atoms on a basis?

I’m not a big fan of using functions generated by macros in application code, it doesn’t play well with LSP and as the modules become more complex, it becomes a source of confusion. Maybe you could redesign the code to work around modules:

circle = Enuma.new(Shape, :circle, [5.0])

case shape do
  Enuma.match(Shape, :circle, [radius]) -> ....
end

The way I did it a few times when I required enums was with functions:

def circle(radius) when is_float(radius), do: {:circle, radius}

case shape do
  {:circle, radius} -> ....
end

While the macro version looks more organized, I think that simple functions are superior as you don’t tie your enum functions to a module, it amounts to easier refactors and you can cram a unlimited number of functions in a module. I am not a big fan of how functionality like defstruct couples with the module, but I am not entirely sure at the same time how a readable alternative would look like.

As it currently stands, it seems too alien for most of the codebases I worked with. Nonetheless, I think such a library might be a great addition to the ecosystem.

Where Next?

Popular in Discussions Top

slashdotdash
Phoenix Live View is now publicly available on GitHub. Here’s Chris McCord’s tweet announcing making it public.
New
lucaong
Hello Elixir and Nerves community, I have been working for a while on an open-source embedded key-value database for Elixir, that I call...
230 14403 124
New
opsb
We’re considering our architecture from a viewpoint of scaling our traffic heavily over the next 6 months. Our current deployment is runn...
New
RudManusachi
What configs will make sense to put to runtime.exs? – A bit of how I configure apps: I have generic configs in config/config.exs, dev...
New
pillaiindu
I want to convert a Phoenix LiveView CRUD website to a CRUD mobile app. What do you think is the easiest way to do so?
New
cvkmohan
The upcoming Phoenix 1.6 release looks very interesting. Became a habit to watch the commits - and - what they are bringing in. phx.gen...
New
shishini
I think this twitter post and youtube video didn’t get as much attention as I hoped I am still new to Elixir, so can’t really judge ...
New

Other popular topics Top

JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
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
AngeloChecked
What learn first? Rust or Elixir Hi Elixir community! I’m here because i want learn a new language. I’m a junior developer and mainly i ...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New

We're in Beta

About us Mission Statement