DEV Community

Discussion on: On Adding Types to Ruby

Collapse
 
erikwhiting88 profile image
Erik

"Sometimes they return an object, other times nil." I don't understand what's wrong with this. Sometimes you want all or nothing, no?

Collapse
 
gosukiwi profile image
Federico Ramirez • Edited

The problem is that subtle bugs can appear when you are not consistent with your return types. For example:

find_person("Mike").greet # => this will error if find_person returns nil

# not even mentioning when LoD is broken
post.comments.first.person.name.titleize # if anything along the line here returns nil, it breaks

A solution to the above is always returning something that quacks like a person, so you can use the null object pattern and create a NullPerson, or even throwing an exception instead of returning nil is preferred.

Alternatively, you can use some kind of optional monad.