newton-peixoto

newton-peixoto

Help understanding protocols and behaviours

Hello everyone can someone please explain to me how do protocols and behaviours work in elixir like I was five years old? I read some article from dashibit but still dont get it. (+1 question) In OOP (my background) we have interfaces and I can ask for a argument that implements specific interface is that a way to to the same in elixir? for example

def hello( animal = %__BEHAVIOUR__{} ), do: sound

Or any other way?

Marked As Solved

adamu

adamu

Behaviours are about modules, Protocols are about data.

Behaviour

Is a list of functions that a module has. It’s useful when you’re doing something and need to say “now I need you to do your bit”.

An example of a behaviour is Plug. When running middlewear on a webserver, it says “OK, now you do your bit to handle this request” for each plug that’s been set up.

You implement behaviours by defining the required functions in a module, and use them by passing that module name into something that expects to be able to call the functions in the behaviour.

Protocols

Is way of doing something with a type of data. It’s useful when you have some data and need to say “I want to be able to do X with this”.

An example of a protocol is String.Chars. It says “this is the way to convert data to a string”. This is used by to_string.

You implement protocols by declaring the implementation for a specific datatype, and use them by passing data into a function that expects to be able to use the protocol for that data.


Here’s your example implemented with a behaviour:

defmodule AnimalBehaviour do
  @callback make_sound() :: atom()

  def hello(callback_module), do: callback_module.make_sound()
end

defmodule Dog do
  @behaviour AnimalBehaviour

  @impl AnimalBehaviour
  def make_sound, do: :woof
end

And with a protocol:

defprotocol AnimalProtocol do
  def hello(data)
end

defmodule Cat do
  defstruct []

  defimpl AnimalProtocol do
    def hello(%Cat{}), do: :meow
  end
end

Usage:

iex(1)> AnimalBehaviour.hello(Dog)
:woof
iex(2)> AnimalProtocol.hello(%Cat{})
:meow
16
Post #4

Also Liked

LostKobrakai

LostKobrakai

Imagine you have a baking machine, which can bake cookies. That machine allows you to provide a custom sprinkle application system as well as a custom system for cutting out the cookies into their final shape.

A behaviour would be used to document that the module you provide to the baking machine has a function (callback) for running the sprinkle application as needed, as well as the cookie cutting as needed.

You cannot check if a module actually implements a behaviour. The baking machine would just try to initialize e.g. the sprinkle application and fail if it’s missing. Often this is called ducktyping.

Now imagine an oven. An oven can bake many things, but those things all need to be properly prepared for baking. Muffin dough need to go in the muffin tray, a cake dough in a cake ring and the stew in a firesafe pot.

A protocol allows the baking logic to define “If something needs to get baked it needs to provide proper preparation instructions”. Then implementations for muffin, cake and stew can implement that protocol, so baking works without the baking logic needing to know how things are prepared in advance.

Protocol implementations can be checked when protocols were consolidated, but I’d argue you usually don’t want to do so as well.

Both are used for polymorphic code execution, but behaviours are around outer code receiving an implementation explicitly. Protocols are about polymorphism based on the type of data at hand.

sodapopcan

sodapopcan

You are on the right track thinking of behaviours and protocols combined as kind of like interfaces (or perhaps abstract classes). There is a separation in FP because behaviour and data aren’t combined. Behaviours define what functions can be called if we are passed a module; Protocols define what functions we can pass a struct without caring about its type (so long as it implements the protocol).

I’m not sure if this will be more confusing but another way to think about protocols, which you can see clearly in @adamu’s example, is they allow you to define a function implementation in one module that will be called by another another.

In practice I don’t think protocols are necessarily that useful in application code, though it very much depends on how you want to organize your code. As the guides call out, if you aren’t writing a library and aren’t concerned with extensibility, you have the option of keeping all the various implementations for different types (structs) in one module, ie, grouping by functions instead of data. The option to use protocols is certainly there, though!

A real world example I have is that I have some structs that can have an image associated with them that I want to store on S3. I want to be able to pass these structs to a function to convert them into an S3 path. Using a protocol you could define these in the structs’ modules themselves:

defprotocol Storage do
  def to_path(struct)
end

defmodule User do
  defstruct [:id, :name, :email]

  defimpl Storage do
    def to_path(%User{} = user) do
      "users/#{user.id}.jpg"
    end
  end

defmodule Product do
  defstruct [:id, :slug, :title]

  defimpl Storage do
    def to_path(%Product{} = product) do
      "products/#{product.slug}.jpg"
    end
  end
end

However, since I own all this code, I just define them in one module:

defmodule User do
  defstruct [:id, :name, :email]
end

defmodule Product do
  defstruct [:id, :slug, :title]
end

defmodule Storage do
  def to_path(%User{} = user) do
    "users/#{user.id}.jpg"
  end

  def to_path(%Product{} = product) do
    "products/#{product.slug}.jpg"
  end
end

Both these implementations result in identical callsites: Storage.to_path(user). I don’t particularly think one implementation is staggeringly better than the other. I personally find the non-protocol version simpler and I have all my S3 pathing stuff in one place, but there are arguments against it too. As always, YMMV.

As for behaviours, they are incredibly useful in application logic. They can be used for implementing the strategy pattern, for example.

gpopides

gpopides

Behavriours → interfaces in OOP with the difference that your function won’t pattern match on a behaviour but a module that has the callbacks defined in the behaviour.

e.g

defmodule A
  @callback do_a()
end
defmodule ImplementationOne
@behaviour A

def do_a(), do: "Implementation 1"

defmodule ImplementationTwo
@behaviour A

def do_a(), do: "Implementation 2"

What you would pattern match on would be ImplementationOne and ImplementationTwo instead of the behaviour

Protocols are about different implementations of a method depending on the type

So, if we have a protocol like:

defprotocol Size

def size(item)

When you implement the protocol for a string, the length function should return the number of characters in the string. But this implementation is not valid for a list. The implementation for the list should return the number of elements in the list. Likewise, this implementation is not valid for maps, for maps we want to return the number of keys in the map.

So, we have 1 method (size) and we have a different implementation based on he type (module)

Where Next?

Popular in Questions Top

sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
johnnyicon
Hi all, I’ve just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I’m trying to use Postgres...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" => #BSON.ObjectId<58eb1a7a9ad169198c3dXXXX>, "email" => ...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New

Other popular topics Top

gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
saif
Hello everyone, Long time lurker first time poster here. I’ve recently begun working on Elixir full-time again! :raised_hands: It’s been...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36128 110
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
klo
Got a question about when to concat vs. prepending items to list then reversing to achieve appending. So i know lists boil down to [1 | ...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
Qqwy
Update: How to use the Blogs & Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3271 126479 1222
New

We're in Beta

About us Mission Statement