DEV Community

Cover image for Using the Keyword module for options
Herminio Torres
Herminio Torres

Posted on

4

Using the Keyword module for options

It would be best if you considered using Keyword.fetch!/2 and Keyword.get/3 for options to APIs.

Without options

defmodule MyApp do
  def config(name, author \\ "Herminio Torres", description \\ "Description") do
    %{
      name: name,
      author: author,
      description: description
    }
  end
end
Enter fullscreen mode Exit fullscreen mode
iex> MyApp.config
config/1    config/2    config/3
iex> MyApp.config("my_app")
%{
  author: "Herminio Torres",
  description: "Description",
  name: "my_app"
}
iex> MyApp.config("my_app", "Change")
%{
  author: "Change",
  description: "Description",
  name: "my_app"
}
Enter fullscreen mode Exit fullscreen mode
  • Creates a config function with many arities
  • You must pass all parameters when you intend to change just the last default argument.

With Options

defmodule MyApp do
  def config(opts) do
    name = Keyword.fetch!(opts, :name)
    author = Keyword.get(opts, :author, "Herminio Torres")
    description = Keyword.get(opts, :description, "Description")

    %{
      name: name,
      author: author,
      description: description
    }
  end
end
Enter fullscreen mode Exit fullscreen mode
iex> MyApp.config([])
** (KeyError) key :name not found in: []
    (elixir 1.12.3) lib/keyword.ex:420: Keyword.fetch!/2
    iex:3: MyApp.config/1
iex> MyApp.config([name: "my_app"])
%{
  author: "Herminio Torres",
  description: "Description",
  name: "my_app"
}
iex> MyApp.config([name: "my_app", description: "Change"])
%{
  author: "Herminio Torres",
  description: "Change",
  name: "my_app"
}
Enter fullscreen mode Exit fullscreen mode
  • The raised error leads you to which options are required
  • Keyword lists make the arguments named
  • Only one function arity is exposed

Awesome!

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is 100% worth it for your career.

Okay let's go

Community matters

Top comments (0)

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay