Groups keyboard shortcuts have been updated
Dismiss
See shortcuts

Add strict option to Keyword.validate

61 views
Skip to first unread message

Mateusz Front

unread,
Aug 28, 2024, 11:30:06 AM8/28/24
to elixir-lang-core
Hi,

WDYT about adding a `strict: boolean` option to `Keyword.validate/2` that would make it return an error if a key that doesn't have a default value provided is absent? The returned value in case of an error could be `{:error, unknown_keys, missing_keys}`, for example:

{:error, [], [:b]} = Keyword.validate([a: :foo], [:a, :b], strict: true)
{:error, [:c], [:b]} = Keyword.validate([a: :foo, c: :bar], [:a, :b], strict: true)
{:error, [:c], []} = Keyword.validate([a: :foo, b: :foobar, c: :bar], [:a, :b], strict: true)

in case of success, the result would remain as it is now:

{:ok, [a: :foo, b: :bar]} = Keyword.validate([a: :foo, b: :bar], [:a, :b], strict: true)
{:ok, [b: :bar, a: :foo]} = Keyword.validate([a: :foo], [:a, b: :bar], strict: true)

The behaviour would be unchanged when the strict is set to false (default). The bang version would be adjusted accordingly.

Thanks ;)

José Valim

unread,
Aug 28, 2024, 11:50:08 AM8/28/24
to elixir-l...@googlegroups.com
We considered this but the error we would raise is generic. It is much better for you to validate afterwards and raise good error messages that say it is missing and which value you should pass instead and what it is used for!

--
You received this message because you are subscribed to the Google Groups "elixir-lang-core" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elixir-lang-co...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/elixir-lang-core/44d14235-d129-4f1c-b9de-7895c610d083n%40googlegroups.com.
Message has been deleted
Message has been deleted

Mateusz Front

unread,
Aug 30, 2024, 3:52:58 PM8/30/24
to elixir-lang-core
Right, I understand. I'd argue that many times there isn't much more to say beyond 'We require this option, please provide it'. Also, a simple way of ensuring the options are there would be very useful when prototyping, as it would prevent from `nil`s sneaking deep into the logic, before friendly error messages are added. 
Reply all
Reply to author
Forward
0 new messages