How to put a if else in a function

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.

1 Like

Please always supply errors and code as text. The images are not readable on my screen, and it makes it very hard to suggest edits because I have to retype everything.

5 Likes

sorry about that i will edit it right now