Is it normal to use "case" all the time?

Hello,

I’d like to kindly ask about using case vs. other statements/conditions.

I different languages (all OOP) I used if/else most of the time. I didn’t use case at all mainly because it needed break and I found if/elseif/elseif/elseif/else better readable.

I spent whole weekend on Elixir (great weekend! ;-)) and now I’m looking at my code and:

I used:

  • case approx 50 times
  • if/else 2 times for if x in some_list and if x > 0 and looking at it now I might replace it by multi-clause function
  • cond 1 time for:
cond do
	n > length -> :error
	length == n -> {:ok, ""}
	true ->  {:ok, do_something_with(x)}
end

And everything else is case (not counting guard clauses/pattern matching in function arguments).

I even used case for stupid things like

case value do
    [] -> :error
    value -> {:ok, value}
end

Can anyone please tell me is this normal in Elixir or am I crazy / crazy love with case ?

P.S. this looks like funny joke question :wink: but it’s actually real and serious questions.

Kind regards,

Mat

2 Likes

Yes, pattern matching is the favored way of doing conditionals in elixir, so it is absolutely normal to use much more case/2 and function head pattern matching than it is to use an if/2 (which at the end is a macro which expands to a case/2 anyway).

3 Likes

I had a similar experience/revelation as you on this point when starting with Elixir. Next step is to wonder at the marvel of with and realize you have written your last nested conditional.

Thank you NobbZ and tfwright.

@tfwright Funny that you mentioned with. Yesterday for the first time I needed to chain two tuple returning functions and thinking how am I suppose to do that without nesting cases. And I discovered with. For two functions not a big deal but if you have a lot of them… big deal :wink: