Behaviours

Luke Gorrie luke@REDACTED
Sun Sep 8 21:19:00 CEST 2002


Mickael Remond <mickael.remond@REDACTED> writes:

> Regarding behaviours, most of the time you need to _use_ an existing
> behaviour (found in the Erlang/OTP framework): You write a module
> that implements specific code and use generic code of a
> behaviour. You should very rarely need to write your own behaviour,
> like you asked in your previous question.

>From my own experience of learning erlang, I think it's easy to get
the feeling that behaviours are more magical than they really are.

Behaviours are very simple: you have one module that does some
general/reusable stuff, and you pass it the name of another module to
call for doing more specific things. So gen_server itself handles
receiving/replying to messages and keeping the state record, and you
tell it which module to call to actually do something with the
messages and choose new states.

It's pretty much the same thing as abstract classes (or interfaces
declaring callbacks) in java, or using a struct of callbacks in C.

The only magic part is the "-behaviour(name)." declaration in the
source file, which AFAIK just makes the compiler check that your
module has defined all the right functions for callbacks.

So to make your own behaviour you just write one general module that
takes the name of another module as a parameter, and have it call some
well-defined functions of that module to do certain things. I think
you can even hook into the compiler for the -behaviour stuff now.

Cheers,
Luke




More information about the erlang-questions mailing list