fireproofsocks

fireproofsocks

Writing multiple specs for multiple function clauses? Or single spec?

I’m confused… when grooming the docs for https://elixir-lang.org/getting-started/typespecs-and-behaviours.html I got the feedback that multiple function clauses require multiple @specs. But now that I’m digging into dialyzer, I’m getting errors in places where I’ve done that. E.g.

Overloaded contract for MyApp.some_function/1 has
overlapping domains; such contracts are currently unsupported and
are simply ignored.

Consider this module:

defmodule MyApp.Helpers do
  
  alias Absinthe.Blueprint.Input.String, as: AbsintheString
  alias Absinthe.Blueprint.Input.Integer, as: AbsintheInteger
  alias Absinthe.Blueprint.Input.Float, as: AbsintheFloat
  
  @spec parse_value(AbsintheString.t() | AbsintheInteger.t() | AbsintheFloat.t() | any()) :: {:ok, String.t()} | {:error, any()}
  def parse_value(%AbsintheString{value: value}) do
    {:ok, value}
  end
  
  def parse_value(%AbsintheInteger{value: value}) do
    {:ok, Integer.to_string(value)}
  end
  
  def parse_value(%AbsintheFloat{value: value}) do
    {:ok, Float.to_string(value)}
  end


  def parse_value(_) do
    {:error, "Invalid value"}
  end
end

Dialyzer seems happy when it has only a single combined @spec, but readability is better when each function clause has its own @spec, something more like this:

  @spec parse_value(AbsintheString.t()) :: {:ok, String.t()}
  def parse_value(%AbsintheString{value: value}) do
    {:ok, value}
  end

  @spec parse_value(AbsintheInteger.t()) :: {:ok, String.t()}
  def parse_value(%AbsintheInteger{value: value}) do
    {:ok, Integer.to_string(value)}
  end
  # ... etc...

Which way is correct?

Marked As Solved

michallepicki

michallepicki

You’re only getting this warning because of the fallback function clause with any. If types for all function arguments overlap, Dialyzer will show a warning (not an error AFAIK) and (I think?) it will use only the last version.

Multiple specs are sometimes useful when you can have different argument types and maybe different return types for them. Separate @spec can look cleaner than a big one with many | ... | ....

But if specs are the same (or overlapping) I would probably use just one. Notice what ex_doc generates for the same specs: it will just list the same thing multiple times.

Also Liked

NobbZ

NobbZ

Both are correct.

Use whichever you prefer, though having multiple specs can lead to “overlapping” specs, which are not allowed.

Also ... | ... | any can be simplified to any.

Last but not least, dialyzer will combine the second version into the first anyway.

fireproofsocks

fireproofsocks

What exactly are “overlapping specs”?

ityonemo

ityonemo

In the example you gave the two typepecs are quite literally identical, so the preimage and range of both “functions” trivially overlaps. Here’s a nonoverlapping typespec with associated function:

@spec foo(a :: :give_me_a_string) :: String.t
@spec foo(a :: :give_me_a_list) :: list
def foo(:give_me_a_list), do: 'foo'
def foo(:give_me_a_string), do: "foo"

I prefer to group my typespecs for distinct function entry points (this is rare) together, and I personally organize spec, doc, function bodies. But these are stylistic choices.

Where Next?

Popular in Questions Top

chokchit
** (DBConnection.ConnectionError) connection not available and request was dropped from queue after 2733ms. You can configure how long re...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
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 records...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New

Other popular topics Top

Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
Lily
In templates/appointment/index.html.eex: <%= for appointment <- @appointments do %> <tr> <td><%= appoi...
New
hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a > b) do {:ok, "a"} end if (a < b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 52341 488
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
klo
Got a question about when to concat vs. prepending items to list then reversing to achieve appending. So i know lists boil down to [1 | ...
New
Qqwy
Update: How to use the Blogs & Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3271 126479 1222
New

We're in Beta

About us Mission Statement