Ignoring the return value

1 min read elixir

Two weeks ago José Valim created a Pull Request in the Phoenix project. One of the things that stood out to me when I was taking a look at it was this line.

Here, José is pattern matching to underscore the result value of the call to Process.monitor/1, which at first looks like an unnecessary match, due to the fact that the result will be ignored.

The full function block looks something like this:

def init({socket, auth_payload, parent, ref}) do
  _ = Process.monitor(socket.transport_pid)
  %{channel: channel, topic: topic} = socket
  socket = %{socket | channel_pid: self()}

  case channel.join(topic, auth_payload, socket) do
    {:ok, socket} ->
      init(socket, %{}, parent, ref)
    {:ok, reply, socket} ->
      init(socket, reply, parent, ref)
    {:error, reply} ->
      send(parent, {ref, reply})
    other ->
      raise """
      channel #{inspect socket.channel}.join/3 is expected to return one of:
          {:ok, Socket.t} |
          {:ok, reply :: map, Socket.t} |
          {:error, reply :: map}
      got #{inspect other}

As he explains:

Yes, we usually do it to say “i know this returns something meaningful, but i am sure i don’t need it”.

This seems to be a good convention to show we won’t use the returned expression, so I will take it into account to use it in the future.