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
dimitarvp

dimitarvp

@Marcus gives you a good way to go about it. I’ll offer one more:

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(%{"a" => a, "b" => b, "c" => c, "d" => d}), do: do_something(Map.merge(params, %{"e" => 10}))
-  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
PJUllrich

PJUllrich

Author of Building Table Views with Phoenix LiveView

Yes, the missing field is always the same.

Thanks a lot for your solution, however it feels a bit overkill :smiley:
But it would be a good solution if any of the fields could be missing.

Where Next?

Popular in Questions Top

sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
New
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
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
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
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
Exadra37
Sometimes I want to check if the input into a function is not a blank string. My first approach: defmodule Example do def do_stuff(s...
New

Other popular topics Top

joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
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 42633 214
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New

We're in Beta

About us Mission Statement