Writing Type Specifications
Learn to define and apply typespecs in Elixir to clearly communicate function usage and improve code readability. Explore how to use Dialyxir for static code analysis to detect bugs and inconsistencies in genetic algorithm functions. This lesson helps ensure your framework's reliability and maintainability.
We'll cover the following...
What are typespecs?
While Elixir isn’t a statically typed language, it does give the ability to specify types using typespecifications, or typespecs. Typespecs are specifications that communicate the intended use of a function.
For example, a function add/2 that adds two numbers a and b might have the following specification:
Notice the syntax used to declare a specification. We use the
@specattribute to indicate that we’re defining a specification, and then declare the parameter types and the return type of the function. The syntax is similar to the syntax you used in the lesson Creating the Problem Behaviour, to define callbacks for yourProblembehavior and to define yourChromosometype.
Defining typespecs for functions won’t do anything to improve the performance of the code; however, it does serve to enhance the readability of the code and can be used by dialyxir to find bugs and other problems ...