DEV Community

loading...

Discussion on: Returning type-safe & non-nil failure in Crystal?

Collapse
asterite profile image
Ary Borenszweig

nil in Crystal is used to represent the absence of a value. If a User doesn't exist in the database you should return nil for that case. Doing so will force caller of the method to always deal with the possibility (they can't forget to do it, unlike the errors suggested alternative).

In short: nil is the way to go.

Collapse
mjb2kmn profile image
MN Mark Author • Edited

Succinct and authoritative, thank you, sir!

I've been trying to avoid nil in crystal because I felt it was the "safe" thing to do (also I didn't want to have to call .as(...) so much).

I think I am finally understanding that it isn't the absence of nil values that provides the safety but Nil being a type that the compiler can check for and enforce proper handling of.