[erlang-questions] the record volates the declared type when I analysis the code

Dániel Szoboszlay <>
Fri Apr 18 12:17:10 CEST 2014


On 2014 Apr 18, at 12:00 , Loïc Hoguin <> wrote:

> On 04/18/2014 11:55 AM, Dániel Szoboszlay wrote:
>> Hi,
>> 
>> I’d recommend you to decouple the type spec from the record the
>> following way:
>> 
>> -record(kv, {key, value}).
>> -type kv() :: #kv{key::string(), value::integer()}.
>> 
>> Bonus feature: you can export the kv/0 type from your module (if you
>> need to), but you can’t do that when the types are embedded into the
>> record declaration.
> 
> I am not sure what you mean by that. I have been doing it for a long time and it works just fine, albeit I always use opaque for exported records.

Well, sometimes two modules need to use the same record (defined in a header of course). Then you can do something like:

-module(foo).
-include(“foorec.hrl”).
-type foorec() :: #foorec{…}.
-export_type([foorec/0]).
…

-module(bar).
-include(“foorec.hrl”).
-spec bar(Foo :: foo:foorec()) -> ok.
…

I like this pattern, because it’s easy to understand who is responsible for the foorec() type, the type spec will end up in the EDoc page and so on.

Anyway, that’s not so important for the original question. What is important is that by separating record declarations from type specs you can clearly explain to Dialyzer via function specs when do you want to deal with a type-correct record and when do you just happen to handle tuples that look like your records (e.g. in match specs or by a random coincidence like in this other question).

Regards,
Daniel
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20140418/bcf1069b/attachment.html>


More information about the erlang-questions mailing list