Hey everyone, this has been on my mind for some time and I’d love your input on it!
TLDR: I feel like maps are superioer for storing and working with configuration options as compared to keyword lists and am wondering what I might be missing
So, in Elixir it seems like Keyword lists are the de facto standard for passing options around. It’s what Mix.Config
does and sort of advocates, to my understanding. Also it is advocated in the guides
These characteristics are what prompted keyword lists to be the default mechanism for passing options to functions in Elixir
The special characteristics mentioned are:
- Keys must be atoms
- Keys are ordered, as specified by the developer.
- Keys can be given more than once
While I agree that the first one is cool/important for options, I don’t see the value of the other two for options as I see them. Given options there is only ever one option and there should be one key/value pair for it (e.g. should this print a warning? How long should this run?) and I don’t care about the ordering of the keys as I just want to get my specific value.
I can clearly see the value of these properties (and therefore Keyword lists) for DSLs like Ecto (as mentioned in the docs as well) but not for options.
In practice I found keyword lists awkward to deal with when used as options. My two main pain points are:
- keys might occur twice while I want exactly one (when I override the value of that one key I probably want it)
- pattern matching is hard (you gotta match on the length of the list and the order of keys) - while I love to pattern match on configuration options
To elaborate on the last point, I found it to be quite nice to pattern match on configuration options to handle them which reads very nice imo:
defp print_configuration_information(_, %{print: %{configuration: false}}) do
nil
end
defp print_configuration_information(jobs, config) do
# do printing magic
end
This is also why I use maps for configuration in benchee.
So in short, I feel like maps are superior for storing and working with configuration options but at the same time I somehow feel like I’m not writing idiomatic elixir and that I’m missing some great advantage of keyword lists.
Opinions/Advice/Insights?
Thanks!
Tobi