...

/

Adding Type Specifications

Adding Type Specifications

Learn how to use type specifications to improve code.

Introduction to type specifications

Type specifications are notations that say what our functions expect and return. In some languages, the compiler uses the type specifications to optimize the code and check its correctness. Elixir is a dynamic language, and the compiler doesn’t use type specifications to optimize our code. However, the Dialyzer tool uses type specifications to do a static check to verify if type usage is correct, catching some hidden bugs. Type specifications are also good for generating documentation, clarifying what is expected in our code. We’ll use type specifications to improve the DungeonCrawl.Room.Trigger.run/2 contract, and we’ll add them to document the expected structures in the function’s arguments and return.

Adding type specifications to the game

The DungeonCrawl.Room.Trigger.run/2 needs a character and a room action. We need to create the character and room types. Then we can specify the run/2 function’s arguments. Let’s define the character type in lib/dungeon_crawl/character.ex, adding the following code:

Press + to interact
@type t :: %DungeonCrawl.Character{
name: String.t,
description: String.t,
hit_points: non_neg_integer,
max_hit_points: non_neg_integer,
attack_description: String.t,
damage_range: Range.t
}

We used the @type directive to start the type definition. That type has the name t, and the code after the :: is the type definition. We’re saying the type is a DungeonCrawl.Character struct composed ...