Improve decode.optional_field
#4182
ghivert
started this conversation in
Ideas & suggestions
Replies: 1 comment
-
This is not the case- there are many other defaults you want to use, and I would suggest that often |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I'm currently rewriting my old decoders with the new gleam/dynamic/decode API, and I think it's time now to talk about areas of improvements, before the stdlib bumps to v1.0.0.
decode.optional_field
Usually, you can reasonably expect every
optional
function to return anOption(a)
. It's written in the name, and that's what you're looking for: indicate me in my code that the optional field has been handled, and returns anOption(a)
. This let the author handling the optional value.But
optional_field
has a different opinion, and forces you to get a default value. So you have to provide a default value, andoptional_field
will automatically default to it if no field can be parsed. In case you want anOption(a)
, you have to write a really convoluted code:In addition that you have to handle the optionality by hand, this also prevents you to handle some specific cases. For example, that code is unable to make a difference between the two JSON
{ "field": null }
&{}
. In both cases,optional_field
will feed the result with the default argument. But it's two different structures, and maybe you want to handle them differently. Maybe you want{}
to succeed and{ "field": null }
to fail, because you expectfield
to always contains a value, or being non-existent at all.I think
optional_field
should not return a default value. In case of error, returns the default valueoption.None
, otherwise returnsoption.Some(a)
. Furthermore, if we consider thatoptional_field
should be rewritten without default value, handling unwrapping ofOption(a)
is really straightforward withgleam/option.unwrap
:Even in case we want to handle a potential optional field that could be optional itself, it's a matter of writing:
But at least, you're free to manipulate the dynamic data as you want, we fine granularity.
Beta Was this translation helpful? Give feedback.
All reactions