Behaviours and protocols
Before we dive into the depths of metaprogramming, we need to discuss some related functionalities of Elixir that provide polymorphic features to the language. These are behaviours and protocols.
Briefly, behaviours provide similar functionality of interfaces from other languages such as Java and protocols provide a means for defining and dispatching function implementations for specific data structures.
Behaviours
Behaviours are not exclusive to Elixir; in fact, this is how Erlang implements the Gen*
patterns. Behaviours are similar to interfaces in
object-oriented (OO) languages. They specify a collection of functions that the module will expose. All the GenServer
modules will have the handle_call
, handle_cast
, and handle_info
functions.
Note
The spelling of behaviour in the core Elixir and Erlang API uses the British English spelling. However, Elixir's parser will allow either spelling.
Similar to interfaces in OO languages, the behaviour definition also helps the...