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

Loïc Hoguin essen@REDACTED
Tue Jun 17 16:25:29 CEST 2014


I wish State#state.key were removed from the language entirely.

You are differentiating "match" and "access" in the function clause, but 
in fact both are a "match". Plus if you match that way you can also use 
guards as needed, which is much clearer than sometimes a function clause 
and sometimes a case clause.

On 06/17/2014 04:21 PM, 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
>

-- 
Loïc Hoguin
http://ninenines.eu



More information about the erlang-questions mailing list