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().







