Modules in Elixir

From Elixir Wiki
Jump to navigation Jump to search

Modules in Elixir

File:Elixir logo.png
Elixir logo

In Elixir programming language, a module is a container for functions, data structures, and other definitions. Modules provide a way to organize code and create reusable components. They are fundamental building blocks for creating powerful and maintainable applications in Elixir.

Defining Modules

A module can be defined using the `defmodule` keyword followed by the module name. It is convention to use PascalCase for module names.

```elixir

defmodule MyModule do

 # module definitions

end

```

Functions in Modules

Modules can contain function definitions. Functions defined within a module are usually invoked using the dot notation (e.g., `Module.function(args)`).

```elixir defmodule MyModule do

 def my_function(arg1, arg2) do
   # function body
 end

end ```

Module Attributes

Attributes can be attached to modules using the `@` syntax. They are used to store metadata or configuration values associated with the module.

```elixir defmodule MyModule do

 @attribute "value"
 # access the attribute with @attribute

end ```

Importing Modules

Other modules can be imported using the `import` statement. This allows easy access to imported module functions without requiring the module name prefix.

```elixir defmodule MyModule do

 import OtherModule
 # Imported module functions can be used directly
 def my_function() do
   imported_function()
 end

end ```

Access Modifiers

Modules in Elixir provide a way to control the visibility and accessibility of functions and variables using access modifiers such as `private` and `def`.

```elixir defmodule MyModule do

 def public_function() do
   # can be called from other modules
 end
 defp private_function() do
   # can only be called from within the module
 end

end ```

Documentation

Modules can include documentation to describe the purpose, usage, and API of the module. This documentation can be accessed using the `h` helper or the `@doc` attribute.

```elixir defmodule MyModule do

 @doc """
 This module provides utility functions for handling strings.
 """
 # Function definitions with documentation
 @doc """
 Returns the length of the given string.
 """
 def string_length(str) do
   # implementation
 end

end ```

Module Attributes

Module attributes can be used for various purposes including configuration, metadata, or storing constants. They are defined using the `@` symbol and are accessible throughout the module.

```elixir defmodule MyModule do

 @api_key "xyz"
 
 # Access the module attribute using @api_key

end ```

Conclusion

Modules in Elixir are essential for organizing code and creating reusable components. They provide a structured and maintainable way to define functions, store data, and control visibility. Understanding the concept and usage of modules is crucial for building robust and scalable applications in Elixir.

See Also