Stratus3D
Stratus3D

Reputation: 4906

When to use an Erlang record instead of a tuple?

When should I use an Erlang record instead of a tuple? Or, visa-versa, when is a Erlang record unnecessary? I am relatively new to Erlang and I am not sure if I am using records and tuples properly. I understand from what I have read that records are essentially stored as tuples behind the scenes.

I typically use records for pieces of data that are going to be passed around the application or persisted somewhere. I use tuples things like the return value of a function, params of a function, and for things that are specific to the body of a function.

Am I using records and tuples correctly? Is there documentation outlining when one type should be used over another?

Upvotes: 2

Views: 450

Answers (1)

I GIVE CRAP ANSWERS
I GIVE CRAP ANSWERS

Reputation: 18879

It is a style question. But do note:

  • Tuples of large arity are hard to get correct and you will easily swap values. A record names each field making swaps less likely.
  • You can easily match on a record for a subset of all fields.
  • A record always needs the same arity. As such they are bad for emulating sum types.
  • Records are not shared over modules which leads to lots of .hrl files with include statements if they are used between modules. This breaks the abstraction.
  • Records can be kept module-local to make it harder for others to use the record. This improves modularity.

Upvotes: 7

Related Questions