When to use a dot in elixir module name?
Asked Answered
W

2

7

I have seen elixir modules named this way:

defmodule Foo.bar.baz do
end

But I can't find any documentation stating when to do this.

Does it have to do with subdirectories? Using mix, I can put my modules in subdirectories within the lib folder, and they work fine without dots.

For example:

# this is in /lib/foo/bar

defmodule Bar do
end

What is the convention?

Waechter answered 30/3, 2018 at 16:54 Comment(1)
AFAIK the convention is to use them when it makes sense to organize your modules this way--noting that modules aren't really hierarchical--they're just atoms, e.g., you can have Foo.Bar.Baz defined without having a Foo or Foo.Bar.Contrabassoon
H
8

There's nothing special about .. You can give a module any name you want as long as it's a valid atom, including e.g. whitespace:

iex(1)> defmodule :"hello world!!!" do
...(1)>   def hi, do: :ok
...(1)> end
iex(2)> :"hello world!!!".hi
:ok

You're also not required to name the modules the same as the file/folder they're in. You can define any module in any .ex file inside lib and they'll be available to the whole application and iex.

The convention, if a file declares a single module at the top level, is to name it based on its path, excluding lib, converting each path segment to capital case. For example, lib/foo/bar/baz.ex usually defines a module named Foo.Bar.Baz.

Homochromous answered 30/3, 2018 at 17:34 Comment(0)
B
4

The convention is only to name all your modules inside your application/package as MyApp.MyModule (assuming that your application/package is named MyApp.) That is more or less similar to java convention to name packages com.example.blah....

This is done to prevent name clashes between different applications/packages.

Elixir core modules are not namespaced (there are some exceptions like String.Chars, though.)

Inside your application/package it is totally up to you whether to choose the flat model for module naming, or hierarchical.

BTW, the module name might be any valid atom. The dot is the convention only, it affects neither mode accessibility for the compiler nor anything else. Module.concat/{1,2} helper uses dot to build up module names, but again this is the convention only.

Bruges answered 30/3, 2018 at 17:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.