Case vs if

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?

1 Like

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.


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.


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