[erlang-questions] Style question: accessing record fields in a function clause pattern match?

Bengt Kleberg bengt.kleberg@REDACTED
Tue Jun 17 16:28:17 CEST 2014


Greetings,

A long time ago it was better to use
1) #rec1{asd=A} = R
then
2) R#rec1.asd

I think it were some additional checks done in the first case.

So a long habit makes 1) my normal choice.

When pattern matching in a function clause I move the matching record
member(s) to the left, and the access ones to the right.


bengt


On Tue, 2014-06-17 at 15:21 +0100, Roger Lipscombe wrote:
> I'm currently refactoring some code, and I've got something like this:
> 
> handle_foo(#state { type = bar, id = Id }) -> whatever;
> handle_foo(#state { type = baz, parent_id = ParentId }) -> whatever.
> 
> ...and I'm wondering whether it's considered bad form to access record
> fields at the same time as matching them in a function clause. I'm
> matching on 'type', and accessing 'id' at the same time, I mean.
> 
> Instead, should I consider something like the following?
> 
> handle_foo(#state { type = bar }) ->
>     Id = State#state.id,
>     whatever;
> handle_foo(#state { type = baz }) ->
>     ParentId = State#state.parent_id,
>     whatever.
> 
> The first form makes it explicit that for different types, different
> fields matter (which might be a smell by itself), but it gets hard to
> see the match on 'type' once I'm accessing more than one or two
> fields.
> 
> I know this is stylistic, and there's no "right" answer; I just
> wondered what other people tend to do?
> 
> Or, more generally, do people prefer using pattern matching to access
> record values, or plain-ol' Foo = State#state.foo expressions?
> 
> Thanks,
> Roger.
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions





More information about the erlang-questions mailing list