amirOrbe
Default arguments best practices?
Hi everyone, I have a function with two parameters with default values something like:
def(param1 \\ %{}, param2 \\ "") do
###
end
this is the best practice for do that? or you know another way ?
Most Liked
zachdaniel
I’ve learned the hard way that if you ever have more than one optional argument its a smell and you should refactor it to an opts list ![]()
srcoulombe
You can also use functions from the Keyword module
def foo(opts \\ []) do
arg1 = Keyword.get(opts, :arg1, "default_value")
...
end
dimitarvp
Absolutely never do this. Your colleagues or even your own future self will forget or be in a hurry just once and introduce a bug that would be difficult to track down.
Either only one optional argument and it must 99% of the time be the last one – unless the differences in type will make it completely obvious if something goes wrong – or use a keyword list as others have said. That approach also allows you to easily name stuff f.ex.
do_stuff(repo, changeset, username: "amir", password: "nope", dob: ~D[2000-01-01])
Last Post!
dimitarvp
Oh, I am not against keyword lists as options, of course. That’s one of the gems in Elixir: it allows you to emulate named function arguments and it is super convenient!
My objection is towards more than one optional function argument (i.e. 2 or more having default values). That becomes messy super quickly.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #security
- #hex









