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 Responses
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])
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
- #javascript
- #podcasts
- #code-sync
- #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
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








