3 ms·
For the author's toy example, I don't see how this is better than using begin... rescue. def weather_for(project) begin project.creator.address.
by aftbit 12y ago
For the author's toy example, I don't see how this is better than using begin... rescue.
def weather_for(project)
begin
project.creator.address.
country.capital.weather
rescue NoMethodError
nil
end
end
- prezjordan 12y agoBecause you may want to chain weather_for with some other methods and have this same "if nil don't break!" strategy. We would end up putting `rescue NoMethodError` everywhere and end up right where we started. Instead, he later changes weather_for to accept and return this new `Optional` construct, making it chainable, and dealing with this "if nil don't break!" in one spot and one spot only.
- nshepperd 12y agoIf that does what it looks like, then Optional is better than that in one respect: begin/rescue will catch all NoMethodErrors, including unrelated ones. But you probably do want an error to be thrown if you typo and write "project.creator.adress" by mistake.