artem

artem

Best approach to replace early exits the elixir way

Hi all

I am still in my early days with Elixir and relatively new to functional languages (did one hobby project in Elm), so most interested in figuring the elixir ways for this or that.

Quite often I am in the situation where I need to have a look at the function input and do an early exit, yet an input validation is something beyond what simple pattern matching or guard could do - a function needs to be called.

For example, in my weather forecast live view there is a handle_event that should only go fetch weather if user has chosen a date already. Otherwise, we just do nothing:

 def handle_event("fetch-weather", _, socket) do
  weatherRow = if (socket.assigns[:target_date] == nil) do
    []
  else
    # actually fill weatherRow with some sensible info
  end
  socket = assign(socket,
      :weatherRow, weatherRow
  )
  {:noreply, socket}
 end

All these argument validation feel to not nice in elixir, but I can’t really think of a good solution.
The best I could think of is about making an original function just extract the data to be validated:

def handle_event("fetch-weather", _, socket) do
  target_date = socket.assigns[:target_date]
  weatherRow = target_date |> handle_fetch_weather_inner
  socket = assign(socket,
       :weatherRow, weatherRow
   )
   {:noreply, socket}
end

defp handle_fetch_weather_inner(nil)
  []
end

defp handle_fetch_weather_inner(nonEmptyTargetDate)
  # Fetch weather using the target date
end

How would you do something like this?
Am I missing some way to pattern match or put guard on the original handle_event?

Marked As Solved

stefanluptak

stefanluptak

Hi @artem, welcome to the forum. :slight_smile:

I sometimes want a simple return ... call too. I was used to having that in in Swift.

Anyway, here’s a gist I made with a few approaches. Somebody will come up with an even more clever one, I guess. But hopefully, this would be useful for you.

If you have a LiveBook, you can open that file and play with it more.

Also Liked

ityonemo

ityonemo

Totally different way:

new_blabla = socket.assigns[:blabla]
|> List.wrap
|> do_the_thing_its_always_a_list

Note List.wrap gives [] on nil. It’s a secret power weapon in elixir.

List.wrap(if something = x.y do: process(something))

is also a common pattern in my toolbelt

artem

artem

Thank you guys, I didn’t realize I could pattern match on map inside a map as

def handle_event3(
        "fetch-weather",
        _params,
        %{assigns: %{target_date: target_date}} = socket
      )

I guess most proper approach is what @stefanluptak posted as handle_event1, for now I’ll try some more function header matching to learn it more. It probably wouldn’t work if I needed some checks with function calls (e.g. validate_date(target_date)), but for my current needs matching works well.

I figured I can even check for the existence of a key as well as in

 def handle_event("fetch-weather", _, %{assigns: assigns} = socket) when not is_map_key(assigns, :target_date) do
    Logger.info("target_date key is missing")
    {:noreply, socket}
  end

  def handle_event("fetch-weather", _, %{assigns: %{target_date: nil}} = socket) do
    Logger.info("handle_event: target_date is nil")
    {:noreply, socket}
  end

  def handle_event("fetch-weather", _, %{assigns: %{target_date: target_date}} = socket) do
    Logger.info("Going to fetch weather")
    ...
  end

Where Next?

Popular in Questions Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&query=perfume&page=2, I would like to get: ...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
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
vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New

Other popular topics Top

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
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
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
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
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
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New

We're in Beta

About us Mission Statement