paseg

paseg

@behaviour, @callback and @spec

Hi

When I use @behaviour and @callback, the functions are defined. I guess that I do not need to use @spec for the implementation of the @impl functions as well?

Will Dialyzer sort this out as well?

Br Patrik

Most Liked

asummers

asummers

You don’t need them as Dialyzer will give a callback does not match spec error, but please include them anyway. As a reader I do not want to have to jump to the behaviour definition to find out what the arguments are. In that vein if you include a using macro where you define default callbacks that are overridable with defoverridable, elide the spec in the using macro, otherwise you’ll get a compiler error for duplicating the spec if anyone actually overrides and wants to spec the override.

YES

defmodule MyBehaviour do
  @callback foo() :: :ok
end

defmodule MyImpl do
  @impl MyBehaviour
  @spec foo() :: :ok
  def foo(), do: :ok
end

YES

defmodule MyBehaviour do
  @callback foo() :: :ok

  defmacro __using__(_) do
    quote do
      @impl MyBehaviour
      @spec foo() :: :ok
      def foo(), do: :ok
    end
  end
end

defmodule MyImpl do
  use MyBehaviour
end

YES

defmodule MyBehaviour do
  @callback foo() :: :ok

  defmacro __using__(_) do
    quote do
      @impl MyBehaviour
      def foo(), do: :ok
    
      defoverridable [foo: 0]
    end
  end
end

defmodule MyImpl do
  use MyBehaviour

  @impl MyBehaviour
  @spec foo() :: :ok
  def foo(), do: :ok
end

NO

defmodule MyBehaviour do
  @callback foo() :: :ok

  defmacro __using__(_) do
    quote do
      @impl MyBehaviour
      @spec foo() :: :ok
      def foo(), do: :ok
    
      defoverridable [foo: 0]
    end
  end
end

defmodule MyImpl do
  use MyBehaviour
  
  # this errors if you include the spec
  # @spec foo() :: :ok
  @impl MyBehaviour
  def foo(), do: :ok
end
paseg

paseg

Hi

Wow, thanks for all comments! Did not know that this would stir up this many opinions. :slight_smile:

A see your point @asummers, but since this is not a public library (“only” used within our company), I prefer that the implementers spend the extra time to go into the definition of the behaviour rather than using multiple specs that will effect the maintenance in the long run.

I also found that the @spec may state less than the actual @callback without Dialyzer telling me, witch gives me another argument not to use the @specs

Example given:

defmodule Register.DocEvents do
  @callback initialize(soure :: binary() | atom()) :: :ok | {:error, String.t()}
end
defmodule Register do
  @behaviour Register.DocEvents

  @impl Register.DocEvents
  @spec initialize(atom()) :: :ok
  def initialize(source) do
    ...
  end
end

Dialyzer signals this is ok, and I guess it is since the actual implementation fits within the original specification. In this case, the @spec makes sense since this implementation is not the same as the @callback stated, but if they are expected to be the same then adding an extra @spec just creates more maintenance burden.

Eiji

Eiji

Sure, here is your changed code:

defmodule MyBehaviour do
  @callback foo() :: :ok
end

defmodule MyImpl do
  @behaviour MyBehaviour

  @doc delegate_to: {MyBehaviour, :foo, 0}
  @doc "Implementation-specific docs goes here …"
  @impl MyBehaviour
  def foo(), do: :ok
end

which would give:

iex(1)> h MyImpl.foo       

                                   def foo()                                    

delegate_to: MyBehaviour.foo/0

Implementation-specific docs goes here …

iex(2)> b MyBehaviour.foo/0
@callback foo() :: :ok

This is much simpler than writing macros or copy-paste documentation and spec.

Generally we should avoid using macros unless it’s required.

asummers

asummers

I wasn’t suggesting to use a macro. Simply saying that if you do have a macro and the function is overridable to elide the spec in the macro (as they do in e.g. GenServer but do NOT elide in HTTPoison). I don’t think they’re incompatible, unless I’m misunderstanding something. This thread is about @spec not @doc.

asummers

asummers

Again, I’m not advocating for the macro, at all, in any way shape or form. I agree in this case it’s not needed. I’m contrasting the approaches taken between GenServer and HTTPoison.Base.


vs.

Dialyzer will pick this all up even if you drop all the @specs. But for readers of the code, giving them the ability to @spec the implementation is much more pleasant (even if they choose not to), because they do not need to look outside the file or inside IEx to be able to figure out what’s going on. And if they have the Credo rule on to require @spec for all functions, you must ignore in the implementation because the compiler will complain about duplicate specs for the implemented callbacks.

Where Next?

Popular in Questions Top

pgiesin
This should be a simple problem but I just can’t seem to figure it out. I have a standalone Elixir app that won’t find the database. Dep...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
kostonstyle
Hi all I want to have a unix time, from the current time plus 1 hour. DateTime.now + 1 hour How to get it in elixir? Thanks
New
chewm
Hi guys, nice to meet you to the whole forum, I’m new here, I’m trying to configure visual studio code for elixir, right now the intellis...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

Other popular topics 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
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
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
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
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New

We're in Beta

About us Mission Statement