Elixir Modules for new developers

This and the other “Deck” posts are a repurposing of flashcard study decks to Q&A blog posts.

What do Elixir developers use Modules for?

Grouping functions with like behavior under a namespace.

How can Modules be nested?

Through a . in the Module definition. In the below example Profile is nested under User:

defmodule User.Profile do 
  def get_details 
  end 
end

What are Module attributes?

They are most often used as constants within a Module but can also be used for documentation of the Module and its functions. In advanced use cases they can used as temporary storage to be referenced in compilation. Below is an example of the constants use case:

defmodule Server do 
  @initial_state %{host: localhost, port: 3000} 
end

Does Elixir have any reserved Module attributes?

Yes. Some of the more common ones are @moduledoc, @doc, @behaviour. More detailed information on these and other attributes can be found here.

In functional programming languages like Elixir how are we able to reuse code? How do modules help with this?

Through a technique called composition. Composition allows us to reuse behavior between Modules. The next few questions will walk through ways Elixir accomplishes this.

If you want to use and reference a module inside another module, what Elixir directive would you use?

The alias directive.

defmodule ProfileHelpers do 
  def from_rds 
  end 
end
defmodule User.Profile do 
  alias ProfileHelpers 

  def get_details ProfileHelpers.from_rds
  end 
end

If you want to use functions defined in one module inside another module without referencing the module directly, what Elixir directive would you use?

The import directive.

defmodule ProfileHelpers do 
  def from_rds 
  end 
end
defmodule User.Profile do
  import ProfileHelpers
   
  def get_details_from_rds 
  end 
end

Is it possible to change the name of a module being aliased?

Yes, by using the as: option when issuing the alias

defmodule ProfileHelpers do
  def from_rds 
  end 
end
defmodule User.Profile do 
  alias ProfileHelpers, as: Helpers 

  def get_details Helpers.from_rds 
  end 
end