PJUllrich

PJUllrich

Author of Building Table Views with Phoenix LiveView

Idiomatic way of handling missing Map fields

I’m extracting many fields from a map using pattern-matching against the function parameter. Sometimes only a single field is missing from the input map. I’m handling this case with Map.merge-ing a default value into the input map and calling the same function again.

However, this feels not quite idiomatic. Can you maybe think of a more idiomatic way of handling this case?

Example:

defmodule Foobar do
  def foo(%{"a" => a, "b" => b, "c" => c, "d" => d, "e" => e}), do: do_something(a, b, c, d, e)

  def foo(params), do: foo(Map.merge(params, %{"e" => 10}))

  def do_something(a, b, c, d, e), do: IO.inspect("#{a}-#{b}-#{c}-#{d}-#{e}")
end

Foobar.foo(%{"a" => 1, "b" => 2, "c" => 3, "d" => 4, "e" => 5})
Foobar.foo(%{"a" => 1, "b" => 2, "c" => 3, "d" => 4})
```

Most Liked

brettbeatty

brettbeatty

I don’t think it’s bad to use Map.merge/2, but the way you use it as a fallback seems weird (and you wouldn’t have a base case if your map didn’t have an "a" key, for example).

Here’s how I would write your module:

defmodule Foobar do
  @default_params %{"e" => 10}
  def foo(params) do
    params = Map.merge(@default_params, params)
    do_something(params["a"], params["b"], params["c"], params["d"], params["e"])
  end

  def do_something(a, b, c, d, e) do
    IO.inspect("#{a}-#{b}-#{c}-#{d}-#{e}")
  end
end

But that may just be because of how I handle options to functions. I write a lot of single-public-function modules where I’m passing around the options to a lot of private functions and want the defaulting to happen in one place. They’ll look something like this:

defmodule My.Service do
  @default_opts %{charlie: true, delta: []}

  def call(alpha, bravo, opts \\ []) do
    opts = Enum.into(opts, @default_opts)

    with :ok <- validate_something(alpha, opts),
         {:ok, echo} <- do_something(alpha, bravo, opts) do
      {:ok, bravo + echo}
    end
  end

  ...
end
PJUllrich

PJUllrich

Author of Building Table Views with Phoenix LiveView

I agree with @Marcus. I’d like to keep on using a map instead of having to define a struct for this function only. But if this case would be occurring in more than one function, the struct would actually be the way to go I think, so thanks :slight_smile:

Marcus

Marcus

@sigu
This case should not be the cause of using a struct. I mean the decision for a struct should be related to the problem and not to using some special syntax.
@PJUllrich
The idiomatic way for me is not to use pattern matching just for the case of extracting values from a map. The pattern matching in the parameters should have always a good reason.

For me foocould be written as:

def foo(data) do
  do_something(
    Map.get(data, "a"),
    Map.get(data, "b"),
    Map.get(data, "c"),
    Map.get(data, "d"),
    Map.get(data, "e", 10)
  )
end

or

def foo(data) do
  defaults = %{"e" => 10}
  %{"a" => a, "b" => b, "c" => c, "d" => d, "e" => e} = Map.merge(defaults, data)
  do_something(a, b, c, d, e)
end

Where Next?

Popular in Questions Top

aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
mgjohns61585
Could someone help me? I’m making my first elixir program, number guessing game. I can’t figure out how to convert the user’s guess from ...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
nobody
How to bind a phoenix app to a specific ip address? could not find anything about that, nowhere, unfortunately, but for me this is quite...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New

Other popular topics Top

TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
274 41539 114
New
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30877 112
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 43622 214
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
boundedvariable
I am going through the kafka architecture. All the features what the kafka is providing are already in Erlang. I would like hear your opi...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New

We're in Beta

About us Mission Statement