Refactoring Elixir

One of my colleagues pointed me at this blog post:

https://evuez.github.io/posts/cursed-elixir.html

This is a refactoring exercise, starting with this:

defmodule FooBar do
  def foo(a) do
    if a < 0 do
      bar(a, -1)
    else
      bar(a, 1)
    end
  end

  defp bar(a, b) do
    IO.inspect(a * b)
  end
end

Transform it into canonical Elixir.

The article linked to moves heavily into pipelines but there are alternatives, here this notes that if is an expression:

defmodule FooBar do
  def foo(a) do
    bar(a, (if a < 0, do: -1, else: 1))
  end

  defp bar(a, b) do
    IO.inspect(a * b)
  end
end

Also bar is symmetrical:

defmodule FooBar do
  def foo(a) do
    if a < 0, do: -1, else: 1 |> bar(a)
  end

  defp bar(a, b) do
    IO.inspect(a * b)
  end
end

Pattern matching and guards is also typical Elixir, more so than an if:

defmodule FooBar do
  def foo(a) do
    a 
    |> calculate() 
    |> bar(a)
  end

  defp calculate(a) when a < 0, do: -1
  defp calculate(a), do: 1

  defp bar(a, b) do
    IO.inspect(a * b)
  end
end

This is far more typical.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s