As it was asked above, perhaps a potential case statement could be…
data =
body
|> case do
nil -> data
body -> Map.put(data, :body, body)
end
It doesn’t look quite so “using CASE statements over IF statements for the sake of being Elixir-ish”
if there is some work to calculate body. For example, if we need to do something like Keyword.get(opts, :body) to calculate body…
data =
Keyword.get(opts, :body)
|> case do
nil -> data
body -> Map.put(data, :body, body)
end
This gives us some pattern matching potential as compared with the IF statement (eg. if this section has to be extended in the future) without adding extra functions.
It’s worth noting that it’s important to not start the pipeline directly (ie. on the same line) after the = as the precedence of data = Keyword.get(opts, :body) is higher than the rest of the pipeline (I learned this the hard way!)…
data = Keyword.get(opts, :body)
|> case do #<--- Won't get here
nil -> data
body -> Map.put(data, :body, body)
end
You can workaround the precedence issue by putting |> case do on the first line too. But “mix format” will rewrite this to the multi-line version I have at the start of my reply anyway. Here it is nonetheless…
data = Keyword.get(opts, :body) |> case do
nil -> data
body -> Map.put(data, :body, body)
end
I’d be interested to here if the approach I suggested (the one at start of my reply) is considered an acceptably idiomatic solution in Elixir - as compared with the suggestions mentioned by others, such as factoring out extra functions, etc.