Erlang Central

Difference between revisions of "Defining Your Own Behaviour"

From ErlangCentral Wiki

Line 22:Line 22:
  
 
== Epilogue ==
 
== 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.
+
This is a really short HowTo and I really debated whether to put this in a howto or just as a recipe in the cookbook. In the end, I figured this question was asked often enough and was important enough to put here.
  
  
 
[[Category:HowTo]]
 
[[Category:HowTo]]

Revision as of 00:59, 3 October 2006

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 recipe in the cookbook. In the end, I figured this question was asked often enough and was important enough to put here.