Skip to content

Instantly share code, notes, and snippets.

@stefanluptak
Created September 9, 2022 13:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stefanluptak/3df11dae8f6db284a472ce80feaf06a6 to your computer and use it in GitHub Desktop.
Save stefanluptak/3df11dae8f6db284a472ce80feaf06a6 to your computer and use it in GitHub Desktop.
Early Exit in Elixir

Early exit

Section

defmodule Channel do
  def handle_event1("fetch-weather", _params, socket) do
    if socket.assigns[:target_date] do
      IO.puts("1 valid")

      # weatherRow = ...
      # assign(socket, :weatherRow, weatherRow)

      {:noreply, socket}
    else
      IO.puts("1 invalid")

      {:noreply, socket}
    end
  end

  def handle_event2("fetch-weather", _params, socket) do
    socket =
      if socket.assigns[:target_date] do
        IO.puts("2 valid")

        # weatherRow = ...
        # assign(socket, :weatherRow, weatherRow)

        socket
      else
        IO.puts("2 invalid")

        socket
      end

    {:noreply, socket}
  end

  def handle_event3(
        "fetch-weather",
        _params,
        %{assigns: %{target_date: target_date}} = socket
      )
      when not is_nil(target_date) do
    IO.puts("3 valid")

    # weatherRow = ...
    # assign(socket, :weatherRow, weatherRow)

    {:noreply, socket}
  end

  def handle_event3("fetch-weather", _, socket) do
    IO.puts("3 invalid")

    {:noreply, socket}
  end
end

Valid

now = to_string(DateTime.utc_now())
Channel.handle_event1("fetch-weather", nil, %{assigns: %{target_date: now}})
Channel.handle_event2("fetch-weather", nil, %{assigns: %{target_date: now}})
Channel.handle_event3("fetch-weather", nil, %{assigns: %{target_date: now}})

Invalid

Channel.handle_event1("fetch-weather", nil, %{assigns: %{}})
Channel.handle_event2("fetch-weather", nil, %{assigns: %{}})
Channel.handle_event3("fetch-weather", nil, %{assigns: %{}})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment