Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between protocol & behaviour in elixir

Tags:

elixir

Behaviours define callbacks & protocols define methods without signatures. Modules implementing a protocol should give definition for all those methods. Same for modules using a behaviour. What is the semantic difference?

One difference I can think of is, a protocol can be implemented for a single type only once where as we can implement a behaviour for a module multiple times based on our requirements. I am clear with when to use what. Is there any other difference other than this?

like image 264
Aravindh S Avatar asked Oct 06 '14 11:10

Aravindh S


People also ask

What protocol means?

A protocol is a set of rules and guidelines for communicating data. Rules are defined for each step and process during communication between two or more computers. Networks have to follow these rules to successfully transmit data.

What is an example of a protocol?

Protocols: It is a set of rules that need to be followed by the communicating parties in order to have successful and reliable data communication. For example - Ethernet and HTTP.

What are the 3 types of protocol?

There are three main types of network protocols. These include network management protocols, network communication protocols and network security protocols: Communication protocols include basic data communication tools like TCP/IP and HTTP.

What is protocol and different types of protocol?

Protocol Definition: It is a digital language through which we communicate with others on the Internet. protocol meaning is that it a set of mutually accepted and implemented rules at both ends of the communications channel for the proper exchange of information.


2 Answers

Protocol is type/data based polymorphism. When I call Enum.each(foo, ...), the concrete enumeration is determined from the type of foo.

Behaviour is a typeless plug-in mechanism. When I call GenServer.start(MyModule), I explicitly pass MyModule as a plug-in, and the generic code from GenServer will call into this module when needed.

like image 122
sasajuric Avatar answered Sep 19 '22 22:09

sasajuric


Answered by José Valim on the same topic ( from google thread, https://groups.google.com/forum/#!msg/elixir-lang-talk/S0NlOoc4ThM/J2aD2hKrtuoJ )

A protocol is indeed a behaviour + dispatching logic.

However I think you are missing the point of behaviours. Behaviours are extremely useful. For example, a GenServer defines a behaviour. A behaviour is a way to say: give me a module as argument and I will invoke the following callbacks on it, which these argument and so on. A more complex example for behaviours besides a GenServer are the Ecto adapters.

However, this does not work if you have a data structure and you want to dispatch based on the data structure. Hence protocols.

like image 45
selvan Avatar answered Sep 20 '22 22:09

selvan