Erlang Central

Defining Your Own Behaviour

Revision as of 00:58, 3 October 2006 by Cyberlync (Talk | contribs)

Why Define a Behaviour?

In general behaviours are just a convenience for the coder. They insure that a module has implemented all the functions it needs to interact successfully with the system that has defined the behavior. So when you are creating a library or application that will be made use of by other libraries or applications with associated callbacks it may be a good idea to define a behaviour.

Defining the Behaviour

All in all, behaviours are pretty simple to define. All you need to do is include a function called behaviour_info with a single argument that is the atom 'callbacks'. The function should return a list of tuples that specify the required callback functions and their arity. It should look something like

-module(some_behaviour).

-export([behaviour_info/1]).

behaviour_info(callbacks) ->
    [{init,1},
     {handle, 1},
     {sync, 2}];
behaviour_info(_Other) ->
    undefined.

This new behaviour requires the functions init/1, handle/1, and sync/2 to be defined in the callback module.

Epilogue

This is a really short HowTo and I really debated whether to put this in a howto or just as a reciepe in the cookbook. In the end, I figured there was enough here to make it a howto.