DEV Community

Starr Horne for Honeybadger

Posted on • Updated on • Originally published at honeybadger.io

Understanding Elixir's Strange Module Names

Last week was amazing. It was our first ever Honeybadger Hack Week. We got to take a momentary break from thinking about exceptions and uptime to focus all our energies on something completely new. We decided as a team to build a small app in Elixir and Phoenix.

As I was getting comfortable with Elixir, one weird thing began to stand out to me. When you open up the console (iex) and type in a module name, there's never an error. Even when the module doesn't exist.

iex> SomeModule
# => SomeModule
Enter fullscreen mode Exit fullscreen mode

This is unlike Ruby, where you'll always get an error:

irb> SomeClass
NameError: uninitialized constant SomeClass
Enter fullscreen mode Exit fullscreen mode

It turns out, Elixir handles module names in an unexpected way. It's a little strange, but once you understand the underlying mechanism, it becomes very easy to reason about modules.

So pull up a seat. Gather round the fire and let me tell you a story.

How other languages handle modules

In static languages like Rust, modules only really exist at compile-time. They're used to perform correctness checks, but then they're discarded and aren't present in the compiled object file except perhaps as debug metadata.

mod sound {
    fn guitar() {
    }
}

sound::guitar();
Enter fullscreen mode Exit fullscreen mode

In Ruby, modules and classes are special kinds of objects. Module "names" are just variables. They have special CamelCase names, and some special lookup rules, but they're basically just variables. You can even reassign them.

module MyModule
  def self.hello()
    puts "world"
  end
end

YourModule = MyModule
MyModule = nil
YourModule.hello
# => "world"
Enter fullscreen mode Exit fullscreen mode

Elixir's surprising approach

At first glance, Elixir looks like Ruby. We can define modules, assign them to variables then call functions as if we were referencing the original.

defmodule MyModule do
  def hello() do
    IO.puts("world")
  end
end

x = MyModule
x.hello()
# => "world"
Enter fullscreen mode Exit fullscreen mode

But there is a difference.

If you're really paying attention you may have noticed that in the ruby example, we have YourModule = MyModule, while in elixir, we have x = MyModule. That's because elixir gives an error if I try the former:

YourModule = MyModule
# ** (MatchError) no match of right hand side value: MyModule
Enter fullscreen mode Exit fullscreen mode

I can assign a module name to a variable, but the module name itself doesn't seem to be a variable like it is in Ruby. Instead, module names are "atoms."

Atoms

Atoms are used to name things when you don't want the overhead of using a string. They're very similar to Ruby's "symbols":

:foo
:bar
:"this atom has spaces and.special.chars"
Enter fullscreen mode Exit fullscreen mode

Common uses for atoms are as keys in maps (hashes in Ruby, objects in JavaScript) and to specify keyword arguments in functions:

my_map = %{foo: 1}
my_func(foo: 1) 
Enter fullscreen mode Exit fullscreen mode

They're also used to name modules. For example, if I want to call Erlang's format function from elixir, I would write something like this:

:io.format(arg1, arg2)
Enter fullscreen mode Exit fullscreen mode

Like all Erlang modules, we reference the io module via an atom, :io.

Aliases

At this point I imagine you're thinking, "Wait a second! Elixir module names look like MyModule not :my_module! Those aren't the same!"

That's because Elixir is playing tricks on us. Behind the scenes, it converts any code referring to MyModule to refer to the atom, :"Elixir.MyModule" . You can see this in action if you open up iex:

MyModule == :"Elixir.MyModule"
# true
Enter fullscreen mode Exit fullscreen mode

The substitution of module name like MyModule with an atom is called "aliasing." It happens automatically for any keyword that looks like a module name: AnythingThatLooksLikeThis.

The reason that we reference Erlang modules directly with atom (:io, etc) is because there's no aliasing involved. Though, if you wanted to you could manually create an alias:

alias :io, as: IO

IO
# => :io
Enter fullscreen mode Exit fullscreen mode

Practical Implications

Now that we know that "module names" in Elixir are just atoms + aliasing, it's easy to reason about modules.

First, we see why we got an error when we tried to assign YourModule = MyModule. When expanded, that code becomes:

:"Elixir.YourModule" = :"Elixir.MyModule"
# error
Enter fullscreen mode Exit fullscreen mode

Assigning one atom to another makes no sense. You might as well try to say 1 = 2 or "foo" = "bar".

Furthermore, we see that anything that can be done with an atom can also be done with a module name:

# Call functions using the atom directly
:"Elixir.MyModule".hello()

Construct module names from strings, dynamically

String.to_atom("Elixir.MyModule").hello()

Pass a module into an anonymous function

(fn x -> x.hello() end).(MyModule)

Make a genserver name equal the current module name

GenServer.start_link(Stack, [:hello], name: MODULE)

Execute the same function in a list of modules

for mod <- [MyModule, OtherModule], do: mod.hello()

Reference a module before it's defined. Just don't run this function if it isn't :)

def do_something(), do: SomeOtherModule.something()

Enter fullscreen mode Exit fullscreen mode




Conclusion

When I first discovered the use of atoms for elixir modules, I wasn't thrilled. It seemed ugly and weird. But I've come around.

Atoms are perfect for naming things, including modules. They're fast. They're never garbage-collected. They're unique. And best of all, they're easy to reason about. Like a lot of Erlang, they make a lot of sense once you get over the intitial strangeness.

Top comments (1)

Collapse
 
edisonywh profile image
Edison Yap

Hey I've seen this blog post before on the Honeybadger blog! (and I listen to Founder's Quest occasionally). Especially loved this one and the Junk Drawer article!

Pretty amazing that you guys have started posting here, that's pretty great, look forward to more (Elixir :p) contents!