Function with many arguments design

If your argument list is always used together, the struct approach can be powerful.

If the arguments are more ad-hoc, one approach you’ll see in other languages is named arguments. Elixir doesn’t specifically have named arguments, but you can get close with a keyword list:

def some_func(required_arg_1, required_arg_2, opts \\ []) do
  # extract optional args from opts with Keyword.get(opts, :optional_arg_name, "default value")
end

# call sequence
some_func("foo", "bar")
some_func("foo", "bar", baz: "wat")

if you have a LOT of optional arguments, you might even do something like:

def some_func(required_arg_1, required_arg_2, kw_opts \\ []) do
  opts = Enum.into(kw_opts, %{optional_arg_1: "default", optional_arg_2:: false, ...})
  # can now use opts.optional_arg_1 etc
  # or pattern-match the map
end

I first encountered this technique in this post: Passing in options: Maps vs. Keyword lists

3 Likes