Yes, now the struct enforces the presence of all the keys. That’s good, because it enforces that an %Entry{}
struct without the necessary options simply cannot be created.
That said, if you don’t want that, you can change the struct definition to:
defmodule Entry do
# remove @enforce_keys
defstruct date: nil, time: nil, title: nil
end
Make sure you understand the implications first though:
-
If you use a struct enforcing the keys, you enforce the presence of the keys whenever that struct gets created. That’s generally better, because it’s the developer’s job to make sure that the struct is created with the correct keys. In other words, it’s not a runtime concern. You still validate that the supplied values are not nil, because those values might come from user input, so that is a runtime concern, and you might need to give meaningful error messages to the user.
-
If you do not enforce the keys, when those keys are not set they will default to
nil
, and your code will return an error tuple like{:error, "input cannot be empty!"}
. This might sound useful, but if it’s the code that builds the struct wrong, an error message to the user won’t be useful.