Rukenshia

Rukenshia

Best Practice to get rid of if...else blocks?

I am used to early returns using the “return” keyword many languages provide.
As I am currently trying to learn elixir, I found it really hard to get a proper structure in my code and avoid if…else blocks which I have to nest very deep.

As an example, I wrote a small bot for Discord (don’t do it by the way, the discord_ex library doesn’t seem to work properly) and have to check several things when I receive a message.

As an example, here is one handler.

defp handle_command({ "msg", "remove-trigger", cmd }, { payload, state }) do
    if payload.data["author"]["id"] == 1234 do
      shortname = String.split(cmd, " ") |> List.first
      if !Messages.has shortname do
        send_message "unknown Message", { payload, state }
      else
        info = Messages.get(shortname)
        trigger = String.replace_leading(cmd, "#{shortname} ", "")
        if Enum.member?(info[:trigger], trigger) do
          Messages.remove_trigger shortname, trigger
          save_messages
        end

        send_message "trigger #{trigger} removed from #{shortname}", {payload, state}
      end
    end
  end

I am pretty sure that this can be way improved - what’s the proper design pattern for that in Elixir, how do I escape the if-block hell?

Most Liked

josevalim

josevalim

Creator of Elixir

To add to this, at some point the community, even Elixir codebase, settled on do_send_message as a convention but today we see it as a bad practice. We are trying our best to not use do_ prefixes in Elixir and use proper function names for them, even if it ends up being the original name with extra information, for example, check_shortname_and_send_message.

atimberlake

atimberlake

You can pattern match the handle_command function to drop the first if

defp handle_command({"msg", "remove-trigger", cmd}, {%{data: %{"author" => %{"id" => 1234}}}, state}) do
   # handle author 1234  
end
defp handle_command({"msg", "remove-trigger", cmd}, {payload, state}) do
  # No-op because you have no else
end

For the second if I would drop the call to Message.has/1 (assuming Message.get/1 returns nil for no message)

shortname = String.split(cmd, " ") |> List.first
do_send_message(Messages.get(shortname))

Then have a function deal with the presence or lack of message

defp do_send_message(nil) do
  send_message "unknown Message", {payload, state}
end
defp do_send_message(info) do
  trigger = …
end

Keep going by creating functions that handle each situation and try to come up with names that reveal the intent of each step (do_send_message is a terrible function name but because naming is hard, you get to solve that :slight_smile: )

Rukenshia

Rukenshia

Thanks a lot guys, this really helped me. It’s really easy for me to forget how powerful the pattern matching just is. I know Rust’s pattern matching which is pretty cool already, but this is way more powerful.

dardub

dardub

I’m new to elixir as well and still figuring this out. But one thing you can do is break this up into more functions and take advantage of pattern matching.

For instance you can get rid of the first if statement by pattern matching the handle_command function:

defp handle_command({ "msg", "remove-trigger", cmd }, { %{data: %{"author" => %{"id" => 1234}}}, state }) do

Where Next?

Popular in Questions Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
logicmason
Hi there, I'm working through my first release with elixir/phoenix. I've built a release with distillery and found that it crashes when I...
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
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
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
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
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
idi527
I’ve been re-reading swift book again and noticed that multiline strings there don’t have a trailing line break, unlike in elixir iex(2)...
New

Other popular topics Top

yurko
Here are few pieces of (common) Linux knowledge that we use for reasonably small one server apps. We use Ubuntu but this should work for ...
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
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
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
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
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement