@impl-attribute on multi-clause functions

When it comes to implementing callbacks of a behaviour (e.g., GenServer) I always struggle whether I should add the @impl-attribute to all function clauses or just to the first.

def Worker do
  use GenServer

  @impl true
  def handle_call(:foo, from, state) do
    # ..
  end
  
  @impl true
  def handle_call(:bar, from, state) do
    # ..
  end
end

What do you think? What are the pros and cons of one way or the other?

1 Like

Only the first one is necessary.

1 Like

Hello, I just add @impl true just to the first function. The benefit of @impl is to get warnings from the compiler and this will be reached with one annotation.

1 Like

It’s worth noting that another benefit of @impl is to signal to the programmer that something is, indeed, a callback implementation. This isn’t as apparent in something as ubiquitous as a GenServer, but when reading a module implementing a less well-known or custom behaviour, this is really nice-to-have info.

1 Like

It’s a little weird, but my personal style is to put the @impl on a standalone function head (when defining multiple clauses for the function).

def Worker do
  use GenServer

  @impl GenServer
  def handle_call(request, from, state)

  def handle_call(:foo, from, state) do
    # ..
  end
  
  def handle_call(:bar, from, state) do
    # ..
  end
end

I guess in my mind it suggests I’m about to define multiple clauses for the same function as opposed to recognizing multiple definitions happen to be for the same function.

7 Likes

Thanks for your feedback.