# Is this code idiomatic Elixir/functional?

**URL:** <https://forum.elixirforum.com/t/is-this-code-idiomatic-elixir-functional/2535>\
**Category:** Questions\
**Tags:** idiomatic-elixir\
**Created:** [November 23, 2016, 2:34pm UTC](https://forum.elixirforum.com/t/is-this-code-idiomatic-elixir-functional/2535 "2016-11-23T14:34:26Z")\
**Posts on this page:** 18\
**Page:** 1

<div class="post-metadata">

**Author:** ![kostonstyle](https://forum.elixirforum.com/letter_avatar_proxy/v4/letter/k/5f9b8f/32.png) [@kostonstyle](https://forum.elixirforum.com/u/kostonstyle)\
**Post date:** [November 23, 2016, 2:34pm UTC](https://forum.elixirforum.com/t/is-this-code-idiomatic-elixir-functional/2535/1 "2016-11-23T14:34:26Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![gon782](https://forum.elixirforum.com/letter_avatar_proxy/v4/letter/g/eada6e/32.png) [@gon782](https://forum.elixirforum.com/u/gon782)\
**Post date:** [November 23, 2016, 2:41pm UTC](https://forum.elixirforum.com/t/is-this-code-idiomatic-elixir-functional/2535/2 "2016-11-23T14:41:00Z")

</div>

> [@kostonstyle](#):
>
> My question is, do I follow functional specification?

What exactly does that mean? It’s not technically a function, no, because it has a side-effect. The reality of Erlang & Elixir is that there can be side-effects in procedures anywhere. Pure functions in these languages are an ideal; something to strive for, not law.

It’s also not law in Haskell, for example, but is clearly marked as happening, at least. I would suggest not fretting about using side-effects in Elixir. Instead, pay attention to where you can do without them by passing data. Don’t do this to blindly follow ideals, but to get code that can be used in any context and with predictable results.

---

<div class="post-metadata">

**Author:** ![hubertlepicki](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/hubertlepicki/32/6822_2.png) [@hubertlepicki](https://forum.elixirforum.com/u/hubertlepicki)\
**Post date:** [November 23, 2016, 2:43pm UTC](https://forum.elixirforum.com/t/is-this-code-idiomatic-elixir-functional/2535/3 "2016-11-23T14:43:35Z")

</div>

You won’t really get pure functions that do operations on databse, files, environment variables etc. etc.

the reason is that they interface with impure external environment. So I do not think there is anything wrong from that point of view in your code.

---

<div class="post-metadata">

**Author:** ![kostonstyle](https://forum.elixirforum.com/letter_avatar_proxy/v4/letter/k/5f9b8f/32.png) [@kostonstyle](https://forum.elixirforum.com/u/kostonstyle)\
**Post date:** [November 23, 2016, 3:01pm UTC](https://forum.elixirforum.com/t/is-this-code-idiomatic-elixir-functional/2535/4 "2016-11-23T15:01:22Z")

</div>

So my code is ok?

---

<div class="post-metadata">

**Author:** ![kostonstyle](https://forum.elixirforum.com/letter_avatar_proxy/v4/letter/k/5f9b8f/32.png) [@kostonstyle](https://forum.elixirforum.com/u/kostonstyle)\
**Post date:** [November 23, 2016, 3:09pm UTC](https://forum.elixirforum.com/t/is-this-code-idiomatic-elixir-functional/2535/5 "2016-11-23T15:09:41Z")

</div>

> [@gon782](#):
>
> Instead, pay attention to where you can do without them by passing data

Can you show me please an example?

---

<div class="post-metadata">

**Author:** ![bbense](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/bbense/32/1074_2.png) [@bbense](https://forum.elixirforum.com/u/bbense)\
**Post date:** [November 23, 2016, 3:13pm UTC](https://forum.elixirforum.com/t/is-this-code-idiomatic-elixir-functional/2535/6 "2016-11-23T15:13:32Z")

</div>

The essential quality of a “pure” function is that it always has the same output for the same inputs.

You could make your function pure by passing in the state of the database and returning the state of the database, However, that’s not really practical. But you should strive to have anything you operate on in the function passed in as an input, rather that magically appearing from the ether.

```
def delete(DB, values ) do
     Kernal.apply(DB, :delete_all, values )
end 

```

This makes the code much easier to test and also limits the side effects to as small a surface area as possible. There is obviously a trade-off between adding needless complexity and applying this principle. To misquote Terry Pratchett

> That’s why there are rules, so you’ll think a bit before you break them.

---

<div class="post-metadata">

**Author:** ![benwilson512](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/benwilson512/32/1457_2.png) [@benwilson512](https://forum.elixirforum.com/u/benwilson512)\
**Post date:** [November 23, 2016, 3:21pm UTC](https://forum.elixirforum.com/t/is-this-code-idiomatic-elixir-functional/2535/7 "2016-11-23T15:21:51Z")

</div>

Hey there. Your function is generally fine, but has a couple of style issues. First, it’d be clearer to use `Enum.any?` instead of `lenght(values) > 0`. Not only is this more readable, we don’t actually care what the length is, so long as there’s at least one item. No point in counting them all.

Secondly, you should just return `:ok` instead of `{:ok}`. There’s no point in wrapping it in a tuple.

With these changes in mind, your best bet is something like:

```elixir
def delete_db(values) when is_list(values) do
  if Enum.any?(values) do
    Repo.delete_all(values)
  else
    :ok
  end
end

```

---

<div class="post-metadata">

**Author:** ![gon782](https://forum.elixirforum.com/letter_avatar_proxy/v4/letter/g/eada6e/32.png) [@gon782](https://forum.elixirforum.com/u/gon782)\
**Post date:** [November 23, 2016, 3:37pm UTC](https://forum.elixirforum.com/t/is-this-code-idiomatic-elixir-functional/2535/8 "2016-11-23T15:37:03Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![benwilson512](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/benwilson512/32/1457_2.png) [@benwilson512](https://forum.elixirforum.com/u/benwilson512)\
**Post date:** [November 23, 2016, 3:47pm UTC](https://forum.elixirforum.com/t/is-this-code-idiomatic-elixir-functional/2535/9 "2016-11-23T15:47:56Z")

</div>

As a final tweak, you can have the second clause just be `def delete_db(values)` because the only way it gets there is if it isn’t an empty list. You could add `when is_list(values)` if you really wanted to as well

---

<div class="post-metadata">

**Author:** ![gon782](https://forum.elixirforum.com/letter_avatar_proxy/v4/letter/g/eada6e/32.png) [@gon782](https://forum.elixirforum.com/u/gon782)\
**Post date:** [November 23, 2016, 3:49pm UTC](https://forum.elixirforum.com/t/is-this-code-idiomatic-elixir-functional/2535/10 "2016-11-23T15:49:40Z")

</div>

> [@kostonstyle](#):
>
> Can you show me please an example?

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.

---

<div class="post-metadata">

**Author:** ![gon782](https://forum.elixirforum.com/letter_avatar_proxy/v4/letter/g/eada6e/32.png) [@gon782](https://forum.elixirforum.com/u/gon782)\
**Post date:** [November 23, 2016, 3:51pm UTC](https://forum.elixirforum.com/t/is-this-code-idiomatic-elixir-functional/2535/11 "2016-11-23T15:51:57Z")

</div>

> [@benwilson512](#):
>
> As a final tweak, you can have the second clause just be def delete\_db(values) because the only way it gets there is if it isn’t an empty list. You could add when is\_list(values) if you really wanted to as well

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

---

<div class="post-metadata">

**Author:** ![benwilson512](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/benwilson512/32/1457_2.png) [@benwilson512](https://forum.elixirforum.com/u/benwilson512)\
**Post date:** [November 23, 2016, 3:57pm UTC](https://forum.elixirforum.com/t/is-this-code-idiomatic-elixir-functional/2535/12 "2016-11-23T15:57:21Z")

</div>

> 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

Well the thing is there’s no value in doing this redundantly. `Repo.delete_all` already checks that the inputs make sense. In fact the whole function is pretty redundant because Repo.delete\_all is smart enough to `no-op` an empty list.

---

<div class="post-metadata">

**Author:** ![gon782](https://forum.elixirforum.com/letter_avatar_proxy/v4/letter/g/eada6e/32.png) [@gon782](https://forum.elixirforum.com/u/gon782)\
**Post date:** [November 23, 2016, 4:00pm UTC](https://forum.elixirforum.com/t/is-this-code-idiomatic-elixir-functional/2535/13 "2016-11-23T16:00:42Z")

</div>

> [@benwilson512](#):
>
> Well the thing is there’s no value in doing this redundantly. Repo.delete\_all already checks that the inputs make sense. In fact the whole function is pretty redundant because Repo.delete\_all is smart enough to no-op an empty list.

In this case it might be redundant, yeah, but in the general case you’ll get better error messages if you force structural matching when appropriate, because you’ll get errors about no function clause matching, which is generally super easy to debug. It’ll force the error earlier and be less messy.

I would add that I don’t think there is any downside to being as assertive as possible anywhere.

---

<div class="post-metadata">

**Author:** ![josevalim](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/josevalim/32/1787_2.png) [@josevalim](https://forum.elixirforum.com/u/josevalim)\
**Post date:** [November 23, 2016, 7:15pm UTC](https://forum.elixirforum.com/t/is-this-code-idiomatic-elixir-functional/2535/14 "2016-11-23T19:15:38Z")

</div>

Here is my take:

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

```

---

<div class="post-metadata">

**Author:** ![orestis](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/orestis/32/1949_2.png) [@orestis](https://forum.elixirforum.com/u/orestis)\
**Post date:** [November 25, 2016, 8:29am UTC](https://forum.elixirforum.com/t/is-this-code-idiomatic-elixir-functional/2535/15 "2016-11-25T08:29:57Z")

</div>

Is really `Enum.any?` a replacement of `length`?

The documentation says:

> Invokes the given fun for each item in the enumerable. It stops the iteration at the first invocation that returns a truthy value. Returns true if at least one invocation returns a truthy value. Otherwise returns false.

When I read this, I would expect that `values` would contain true/false values and as long as one of them is true… delete from the repo? I would flag this as a code smell, no?

---

<div class="post-metadata">

**Author:** ![NobbZ](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/nobbz/32/27235_2.png) [@NobbZ](https://forum.elixirforum.com/u/NobbZ)\
**Post date:** [November 25, 2016, 8:59am UTC](https://forum.elixirforum.com/t/is-this-code-idiomatic-elixir-functional/2535/16 "2016-11-25T08:59:18Z")

</div>

`Enum.any?/2` might gain you a bit, but only a little. For an empty list it returns always `false`, so you could do `Enum.any?(list, &(&1))`, which will return `true` for any non-empty list that does not consists of only `nil`s and `false`s. But if you expect to have a list that might consit only of those, you can extend the filter: `Enum.any?(list, &(&1 or (&1 == false) or (&1 == nil)))` (untested).

But to be honest, I’d prefer to use [`Enum.empty?/1`](http://elixir-lang.org/docs/stable/elixir/Enum.html#empty?/1), but only if you can’t use a pattern match.

---

<div class="post-metadata">

**Author:** ![hazardfn](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/hazardfn/32/2761_2.png) [@hazardfn](https://forum.elixirforum.com/u/hazardfn)\
**Post date:** [November 25, 2016, 2:31pm UTC](https://forum.elixirforum.com/t/is-this-code-idiomatic-elixir-functional/2535/17 "2016-11-25T14:31:12Z")

</div>

Was hoping somebody had posted this method - too often the beauty of pattern matching in function heads is forgotten! 😛

---

<div class="post-metadata">

**Author:** ![peerreynders](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/peerreynders/32/5826_2.png) [@peerreynders](https://forum.elixirforum.com/u/peerreynders)\
**Post date:** [November 25, 2016, 3:17pm UTC](https://forum.elixirforum.com/t/is-this-code-idiomatic-elixir-functional/2535/18 "2016-11-25T15:17:32Z")

</div>

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.
