kostonstyle

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

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

josevalim

Creator of Elixir

Here is my take:

def delete_db([]) do
  :ok
end
def delete_db(values) do
  Repo.delete_all(values)
end
gon782

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

peerreynders

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.

gon782

gon782

Think of it this way:

If something needs updating, let’s say a map of some keys and values, you could conceivably have a process that guards that state and the way you interact with it is to send messages to that process in order to modify the data.

When you use this model you run the risk of having the process crash on you, possibly losing state while doing so, and also having the data modified at any point because other processes can also change the state. What you’ve effectively created is something like a reference to the state you want to work with. Sure, when you have it in your hand you can trust that it’s the same state you got from the KV process, but you can never trust that you have the “correct” data in the sense that it’s the updated one.

The BEAM is great in that your particular piece of memory that holds the data you have can’t be changed by anything else, so that’s great, but putting too many things in processes and calling stateful functions with them will still invite harder debugging.

If you had a function that modified the map and then passed that map to the function as an argument everything that that function relies on is inside that function. It doesn’t make any assumptions about the world; for example that a KV store is running somewhere.

It’s trivial to emulate stateful constructs in Elixir, but we generally never set out to do so unless it’s really needed. The point is to make the least amount of assumptions possible about what exists when you run something. The ideal is for everything that a function touches to be something it’s given up-front.

Where Next?

Popular in Questions Top

pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
kostonstyle
Hi all I want to have a unix time, from the current time plus 1 hour. DateTime.now + 1 hour How to get it in elixir? Thanks
New
wernerlaude
In AR this is so simple @articles = current_user.articles How to do in Ecto? def index(conn, _params) do current_user = conn.assig...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New

Other popular topics Top

shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New

We're in Beta

About us Mission Statement