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

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
LegitStack
I’m hoping you guys can give me some general advice and perhaps code examples if you’re feeling up to it. I’m very interested in Elixir,...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
Werner
Hi, I’m using Ubuntu 18.04 and after updating to OTP-24.0 yesterday i have this warning when I run “mix local.hex”: 14:57:30.512 [warn] ...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
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
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
wernerlaude
In AR this is so simple @articles = current_user.articles How to do in Ecto? def index(conn, _params) do current_user = conn.assig...
New

Other popular topics Top

srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
Tee
can someone please explain to me how Enum.reduce works with maps
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
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 45766 226
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
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
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New

We're in Beta

About us Mission Statement