Legible Timeouts with Erlang’s
By convention, timeouts in Erlang (and Elixir) are set in units of milliseconds. However, this isn’t type checked by either language, so you end up with magic integers for timeouts throughout a codebase.
While both Erlang and Elixir support underscores in numbers for readability:
5_000, you’re still expected to know that timeouts are in milliseconds.
timer provides legible helper functions for expressing timeouts:
timer:seconds/1 timer:minutes/1 timer:hours/1
Each takes an integer and converts it from the stated time to milliseconds.
timer also provides
timer:hms/3 for hours, minutes, and seconds, returning their sum in milliseconds.
:timer in Elixir
Elixir supports seamless integration of Erlang standard library functions, though the syntax is a bit different:
So you can replaceI’ve considered using an opaque type to force the use of legible functions, but that would involve wrapping every function in Erlang and Elixir that uses a timeout, which isn’t practical.:
Next time you need to set a timeout in Erlang or Elixir, consider using
timer to embed your design decisions and communicate without magic numbers.Thanks to Zach for pointing me to