Fl4m3Ph03n1x
Guard test breaks the opacity of its argument
I have the following code where I test for the existence of an ETS table:
case :ets.whereis(:metrics) do
:undefined -> {:error, :table_not_created}
tab when is_reference(tab) -> {:ok, :ready}
_ -> {:error, :unable_to_veify_table}
end
However, the clause is giving a weird error:
Guard test is_reference(_tab@1::ets:tid()) breaks the opacity of its argument
What does this mean and how can I fix it?
Marked As Solved
LostKobrakai
The point of opaque types is that the module, which defines the type has functions, which know how to handle the data. In the case of ets the :ets module knows what the data behind tid() is and what to do with it. new does return it, while lots of other functions use it. It does not matter if the current implementation of tid is an integer or a reference, as any code which is not inside of :ets is just supposed to hold on to the value, but not look at what’s inside. This allows :ets to refactor what tid() actually is without breaking client code.
Another example of an opaque type is MapSet.t. Behind the scenes mapsets are implemented using a map. But a map alone cannot guarantee the uniqueness required for sets. Therefore the datatype needs to be opaque so that (in a perfect world) nobody ever directly manipulates the data, but people need to use functions on the MapSet module for manipulation. The module can then guarantee that the constraints of a set datatype are adhered to.
Like mentioned for :ets the implementation for MapSet did already change over the livetime of elixir as well.
There are also tradeoffs to be made when using opaque types:
Only the single module defining the opaque type can actually do something with the data it holds. So the module needs to have functions for everything a client might want to do with said data. No other module can enhance or alter the behaviour around it without breaking the type contract.
Another caveat for opaque types is that you need to be careful with longterm storage of such types. If the runtime updates, but the stored value doesn’t it can result in failures.
Also Liked
garazdawi
It actually used to be an integer not very long ago, so :ets is a very good example of this.
LostKobrakai
You can’t really fix it. :ets.whereis returns the opaque type tid() but your guard clause does typecheck on it. This means you’re dealing with internals you’re not supposed to deal with.
sasajuric
You can rely on the fact that all the :ets functions work correctly if you pass them the result of :ets.new, regardless of what the actual return value is. As long as you do that, and don’t assume anything about the actual data in the tid type, you shouldn’t experience any breaking changes if the tid type is changed.








