Defining Your Own Behaviour

From Erlang Community

(Difference between revisions)
Revision as of 00:59, 3 October 2006 (edit)
Cyberlync (Talk | contribs)

← Previous diff
Current revision (09:50, 26 June 2007) (edit) (undo)
Mazen (Talk | contribs)

 
(4 intermediate revisions not shown.)
Line 23: Line 23:
== Epilogue == == 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. 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.
- +:I think it would be a good idea to give an example on how to actually use the behaviour as it is probably something that is very valuable for a newcomer. A tutorial should be end-to-end imho.
[[Category:HowTo]] [[Category:HowTo]]

Current revision

[edit] 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.

[edit] 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.

[edit] 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.

I think it would be a good idea to give an example on how to actually use the behaviour as it is probably something that is very valuable for a newcomer. A tutorial should be end-to-end imho.
Erlang/OTP Projects
Personal tools