[erlang-questions] Exporting a record type

Jesper Louis Andersen jesper.louis.andersen@REDACTED
Fri Jul 10 13:25:11 CEST 2015


On Fri, Jul 10, 2015 at 2:05 AM, <lloyd@REDACTED> wrote:

> I've asked Loïc Hoguin directly about this, but I thought an elaboration
> and discussion might be of interest to many on this list.


The general idea is: "prefer loose coupling".

Whenever you stuff a record into a header file, every user of that header
file becomes tightly coupled to each other. This means, should the record
change structure, that you have to go hunting for all the uses and make
sure they do the right thing.

If you, on the other hand, define a local record:

-module(foo).

-opaque t() :: #state{}.
-export_type([t/0]).

then type 't' is now local to the module, and thus users can only
manipulate it with functions from the 'foo' module.

This is far more modular, as you have a well-defined API in foo that
explains "what you can do with the type 't'". Generally you want to avoid
module 'foo' to contain getter/setter pairs and define the "transactional"
states that can happen to 't'. That way, the semantics of 't'-transitions
are rigidly defined in module 'foo' and you know where to change the
semantics (in module 'foo').

Of course, there are exceptions to the rule where it is better to share a
record. But my experience is that you want to keep the records as close to
the using modules as possible. Another common thing is that people stuff
their .hrl's into the "include" directory rather than in "src", so they are
exportable and reachable by other applications. This is needed at times,
but again: you are now tightly coupling applications together, not only
modules. And you need to be sure this is what you want.

General dictum: control the scope of records harshly, for they breed like
rabbits in a grassy field.

-- 
J.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20150710/e592465d/attachment.htm>


More information about the erlang-questions mailing list