Skip to content

Instantly share code, notes, and snippets.

@madlep
Created November 17, 2015 10:34
Show Gist options
  • Save madlep/d102f5cb1d578064d0c4 to your computer and use it in GitHub Desktop.
Save madlep/d102f5cb1d578064d0c4 to your computer and use it in GitHub Desktop.
which is preferable style: destructuring struct with pattern matching in function definition, or accessing struct members in function body?
defmodule Foobar do
defstruct :my_field, :another_field
def do_a_thing_destructure(%Foobar{my_field: mf, another_field: af}) do
something_else(mf, af)
end
def do_a_thing_struct_access(foobar = %Foobar{}) do
something_else(foobar.my_field, foobar.another_field)
end
end
@msaraiva
Copy link

I prefer #1. My reasons:

  1. Explicitness: If your function depends only on :my_field and :another_field, I think it's much better to define those dependencies explicity in the function's signature.
    This way it's easier to reason about the behaviour of the function.
  2. Easier to test: Since the dependencies are explicitly, you don't have to "parse" the body of the function looking for which fields you need to setup to get the test running
  3. Compile time check: In #1, if the name of one of those fields changes, you get a compile time error right way. In #2, you'll only get an error in runtime, maybe in production.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment