travisf

travisf

I’m curious what the consensus (if there is one) on case vs if statements for conditionals is. Specifically, in cases where you are only dealing with boolean options for example not is_nil(value).

Personally, when I write Elixir I find that I reach for case way, way more than if even when if would work fine. I think I do it because I don’t always know all the potential conditionals when I start writing the function, I like the sort of open ended nature of case as one can add other cases over time. I also just find something visually unappealing about if statements compared to case when I read Elixir code.

I’m not totally against if I use it from time to time when I know that there will only ever be two conditions or when I can do a single line: if foo, do: func(foo), else: func(bar).

Is this an anti-pattern is there a good reason why I should start using if more regularly?

Showing Posts 1 to 10

stefanchrobot

stefanchrobot

I think that if works great for boolean conditions and it’s often used in the Elixir’s codebase. I’d say that case with just true/false feels weird.

eksperimental

eksperimental

I pretty much feel the same way you do.

I think if/2 is a good fit when you have:

  • no other nested ifs under it,
  • when you check for truthy/false values.

Other than that I prefer to use case and cond. cond is particularly useful for replacing nested ifs or if/elseifs.

travisf

travisf OP

Thanks for the responses. I was worried I was overusing it from a style perspective but this all makes sense.

pierrelegall

pierrelegall

I experienced this in a Credo report today:

Refactoring opportunities
┃ [F] → Cond statements should contain at least two conditions besides `true`,
┃           consider using `if`  instead.

Not convinced by this rules :confused:

t0nghe

t0nghe

I was doing LeetCode and was solving a problem by reducing an enumerable, where the reducer does different things to the accumulator based on whether a condition is true or false.

I didn’t think much about the difference between if-else and case. So I did this:

case MapSet.member?(acc, item) do
  true -> {:halt, true}
  false -> {:cont, MapSet.put(acc, item)}
end

And the runtime was 655 ms, better than 25% solutions.

I tried using if instead, the runtime was 525 ms, that is 100 ms shorter and better than 100% solutions.

In conclusion, if you are only dealing with true or false, if-else is definitely faster.

D4no0

D4no0

Yeah absolutely doesn’t make any sense. case is an erlang construct that is considered a core operation, while if is a syntactic sugar (AKA macro) that uses case under the hood, you can inspect the source code yourself.

ityonemo

ityonemo

More than that if does more work: it’s checking falsiness.

But I still use if. Usually your conditionals are not bottlenecks and it’s easier to read.

D4no0

D4no0

Absolutely, however I would strongly recommend to read this topic: https://forum.elixirforum.com/t/my-thoughts-on-the-if-statement/61985 .

There is a clear intent difference between using case with true/false and if.

t0nghe

t0nghe

Thanks for sharing! I didn’t know that until now. (This is mental!)

I’m reading the source code and saw optimize_boolean, tbh I have zero idea what this is. Is it this what makes if slightly faster?

D4no0

D4no0

My assumption is this is a compile-time optimization, for example you have the following case:

a = true

if a == true do
...
end

This statement can be evaluated at compile-time, hence there is no need to execute the case statement.

In your case, if that is the case, then you literally can optimize if out of your codebase, so it makes no sense in benchmarking if vs case.

Where Next? Top

Trending in Discussions Top

AstonJ
As the title says, please share what you’ve been up to with Elixir. Whether that’s been learning it, looking into it, making stuff with i...
2977 92995 915
New
AstonJ
The obligatory hello world thread! Who are you and where are you from? :stuck_out_tongue:
4616 55835 594
New
caslu
I want to open this thread for you all to discuss and help those who really like Ash but are still hesitant to use it in a real project. ...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
Herve37
We’re evaluating API mocking tools for OpenAPI-based projects and would love to hear what other teams are using. We’re particularly inte...
New
GES233
I’m posting this in response to Jose’s recent tweet (Cr. link) : People are sleeping on Elixir for a coding harness: Hot-code swappi...
New
_mfierro
Hello, I wrote Stop My Hand, a Scattergories-like web application using Phoenix/LiveView as my learning project for Elixir (after readin...
New

Other Trending Topics Top

garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
wintermeyer
There are three potential reasons for members of this forum to have a look at https://vutuv.de You are tired or annoyed of LinkedIn. Yo...
New
webofbits
Aludel - LLM Evaluation Workbench Aludel is an embeddable Phoenix LiveView dashboard for evaluating and comparing LLM prompts across mult...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews