Chris Pressey cpressey@REDACTED
Mon Sep 9 02:09:39 CEST 2002

On Sun, 8 Sep 2002 09:20:39 -0700
"Alex Peake" <apeake@REDACTED> wrote:

> Thank you Francesco.
> I guess the answer is that there is nothing "of a tutorial nature".
> I was looking for more of:
> What is a behaviour? When do you need one? How do you build one?
> (I saw a quote from Joe Armstrong something of the nature that -- in
> Erlang you do not need objects because you have behaviours -- so I
> wanted to explore what this meant)
> Alex

To add my spin on this - clarifying or not  :)

What is a behaviour?

Like an object class, a behaviour is a way of generalizing code.  Unlike
an object class, the generalized code is not specialized by overriding
methods, but rather, by supplying callbacks.

When do you need one?

You benefit from using a behaviour whenever you have several different
components which follow a common pattern.  Like a regular module, the
behaviour can encapsulate the common code used by the components.  Unlike
a regular module, the behaviour can define the interface the components
will share, including callbacks that are used by the common code.

Usually, the module which implements a behaviour can be thought of as a
"callback module" - the functions it exposes will be called by the common
code in the behaviour.  (However, I don't think it necessarily stops there
- the behaviour can specify what functions the implementing module should
expose for ANY purpose - although that could be viewed as feature abuse.)

How do you build one?

You write a module which exports a behaviour_info/1 function.  This
function, when called with the atom 'callbacks', should return a list of
{Function, Arity} tuples, which specify the functions that each module
that implements this behaviour should export.  The behaviour_info function
is used by the compiler to ensure that modules which claim to implement
that behaviour, really do.

Anyway, that's my analysis of behaviours based on how they work, rather
than what they're intended for.  I tend to use them much as I would use
abstract base classes if I were to do OO programming - except that the
inheritance tree tends to be much shallower.  A behaviour which itself
implements a behaviour is a rare thing, but occasionally appropriate.


More information about the erlang-questions mailing list