Simple cascading conditions: what is idiomatic?

This doesnt seem idiomatic, whats better?


Whats the elixir for: Did the web request pass? Did body decode to JSON? Does a value in the JSON match a specific value?

def does_value_at_key_for_some_url_match_something do

  {:ok, %HTTPoison.Response{body: body, status_code: status_code}} = get(
  case status_code do
    200 ->
      {decoded, body} = Poison.decode(body)
      case decoded do
        :ok ->
          body["SOME_KEY"] == "SOME_VALUE"
        _ -> false
    _ -> false

Have a look at this dicussion:

1 Like

sweet! reference are of course best! thx man!

Use Elixir’s with keyword:

def does_value_at_key_for_some_url_match_something(host, url) do
  with {:ok, %HTTPoison.Response{body: body, status_code: 200}} <- get(host, url),
       {:ok, decoded} <- Poison.decode(body) do
    decoded["SOME_KEY"] == "SOME_VALUE"
    _ -> false

Essentially with relatively simple examples like yours you use with.

However it’s just my personal opinion that for larger pieces of code it becomes quickly unwieldy as it tends to expose too much detail and the overall intent of the code can get drowned out in all that noisy detail.

Obviously there are some people who like all their details compressed into one small (but more often than not growing) area - to me lots of JavaScript code reads like this. I prefer code that communicates it’s intent clearly without having to resort to comments (or requires excessive/massive coding idiom pattern matching in my head).

So often with is often a good place to start with but there are various ways of dealing with the problem as the code grows.


good grief! plainly i didnt re-re-read the docs that 3rd and necessary time!

thx community!