Pain Free Documentation with Elixir.

October 18, 2021

Documentation Matters

When writing a program, particularly a program that you expect other people to use, documenting how the program works is a critical step in creating a useful interface. If you want to write a tool that has a chance of being used by other developers, they will need to know how to use that tool. If you want to build a library that doesn’t make people want to rip their hair out in frustration, providing an easy method for them to understand the interface is key to a successful project.

Documentation is Hard

An unfortunate reality of writing good documentation is that doing so is a lot of work. It takes time that could be used on development and most developers have a low threshold of tolerance for writing explanations for their code. Another aspect of what makes documentation difficult is that any time the code base changes, the documentation needs to change. This causes an endless loop where documentation can be a dragging force on a teams development cycle. This is exactly why so many useful projects are made annoying to use, due almost entirely to the absence of quality docs.

Elixir Treats Documentation as a First Class Citizen

The way that Elixir handles this challenge is super cool in my opinion. Elixir provides a package built into the standard library called ex_doc which automatically converts the elixir built-in @moduledoc and @doc annotations into a styled html page which uses the same structure and style of the official language documentation.

ex_doc-example ex_doc example

Being able to produce well formatted and easy to use documentation, without a context change, is an amazing feature that I hope starts to become a feature in all modern languages.

If you want to give this a shot here is a quick example of how to use this feature.

defmodule Cards do
  @moduledoc """
    Provides methods for creating and handling
    a deck of cards.
  """

  @doc """
    Returns of List of Strings representing
    a deck of playing cards.
  """
  def create_deck do
    values = ["Ace", "Two", "Three", "Four", "Five"]
    suits = ["Spades", "Clubs", "Hearts", "Diamonds"]

    for suit <- suits, value <- values do
      "#{value} of #{suit}"
    end
  end
end

All that you need to do to turn the above annotations into a doc site is to run the command mix docs which will generate a full html site for your documentation.

Credit to Stephen Grider and The Complete Elixir and Phoenix Bootcamp. I am using this udemy course to learn the elixir language and it has been great so far, definitely recommend if you want some help learning to use elixir.


Profile picture

William Vincent
Husband, Father, and Software Developer
Check out my personal site!