IvanR
Is it overprotective to have defaults validation with TypedStruct and TypedEctoSchema?
Dear community,
There are lovely TypedStruct by @ejpcmac and TypedEctoSchema by @bamorim libraries to define structs in combination with t() types.
Using them, I missed the validation of default values conformance to t(). That validation seems good because initial default values defining the app’s state can drift from the type definition later as the code evolves. That, in turn, can confuse the local thinking about what’s correctly defined the value or the type?
To address this, I’ve added the compile-time defaults validation feature to the Domo library. That works for any struct that has a t() type defined. And can be activated by adding use Domo like the following:
defmodule Order do
use TypedStruct
use Domo
typedstruct enforce: true do
field :id, non_neg_integer()
field :items, [String.t()], default: []
end
end
That gives the compile-time error highlighting the issue immediately ![]()
Compiling 1 file (.ex)
Domo is compiling type ensurer for 1 module (.ex)
== Compilation error in file lib/functional_core_struct.ex:55 ==
** A default value given via defstruct/1 in Order module mismatches the type.
"Invalid value nil for field :id of %Order{}. Expected the value matching the non_neg_integer() type."
And adding default: 1 option to field :id or changing its type to non_neg_integer() | nil leads to successful compilation.
How do you see it can be worthful to your projects?
Most Liked
dimitarvp
This is extremely useful. I’d use the hell out of it!
ejpcmac
Hello @IvanR, thank you for mentioning me here, you’ve just made me aware of Domo
This seems very neat!
I am not writing much code in Elixir these times, doing mainly embedded stuff in Rust at home (and C / Python at work), but be sure I’ll use it on my next projects using Elixir (certainly some Nerves firmware communicating with other embedded systems written in Rust) ![]()
Validating the default values was on my roadmap, but since you’ve solved it in an elegant way and I
want TypedStruct to be thin, can I mention it in the README / docs as a solution for this?
Popular in Discussions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance










