Is there a better way to do this (handling an optional query parameter)?

Here is a suggested code to handle the optional parameter sub_id:

defmodule IndexController do
  def index(conn, %{"main_id" => main_id} = params) do
    # retrieve sub_id from parameter with a nil fallback
    sub_id = params |> Map.get("sub_id", nil)
    render(conn, "index.html")
  end
end

Is there a better way to do this? Using for example when?

You can have two clauses…

def index(conn, %{"main_id" => main_id, "sub_id" => sub_id} = params) when not is_nil(sub_id) do
def index(conn, %{"main_id" => main_id} = params) do
2 Likes

FYI I believe Map.get/2 returns nil by default, so you wouldn’t need to specify the fallback

1 Like