kostonstyle
Is this code idiomatic Elixir/functional?
I wrote a a function that delete the content of database.
Consider following code snipped:
defmodule Seeds do
def delete_db(values) when is_list(values) do
cond do
length(values) > 0 ->
Repo.delete_all(values)
true ->
{:ok}
end
end
end
When I call the delete_db function, it will happen a side effect, the data on db will be deleted.
My question is, do I follow functional specification?
Thanks
Most Liked
gon782
Well, with refactoring in mind it might be better to simply do this:
def delete_db([]) do
:ok
end
def delete_db([_h | _t] = values) do
Repo.delete_all(values)
end
It’s short, splits the procedure up into cases neatly and asserts structure at the same time.
josevalim
Here is my take:
def delete_db([]) do
:ok
end
def delete_db(values) do
Repo.delete_all(values)
end
gon782
The possible issue is that you’re not necessarily asserting that it should be a list if you ended up using only values, yeah. I prefer code to be as assertive as possible about structure and constants if possible. If something in the function itself makes the assumption that lists are passed in, we should try to make things that don’t follow that crash horribly, IMO.
On a related note: I vastly prefer the structural form to is_list().
Last Post!
peerreynders
This topic made me realize that I need to work more on retraining my mind to see multiple function clauses not as overloaded functions but as distinct parts of one single function.
Edit: Sorry meant to be a general remark, not a specific reply.
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
- #forms
- #api
- #metaprogramming
- #security
- #hex









