monterail / guidelines

[DEPRECATED] We are Ruby on Rails experts from Poland. Think hussars. Solid & winged. These are our guidelines.
71 stars 17 forks source link

Use Hash#fetch instead of Hash#[] #110

Closed sheerun closed 11 years ago

sheerun commented 11 years ago

So the error is visible immediately and not "undefined method ... for nil:NilClass"

jandudulski commented 11 years ago

Do you propose using fetch in absolutely every case?

teamon commented 11 years ago

Same as with any other method call, hash#[] is no different, this is ruby, you can get nil enywhere, using fetch gives nothing really.

{:a => nil}.fetch(:a).foo # => still NME
szajbus commented 11 years ago

@teamon Consider another use case:

{:a => nil}.fetch(:b).foo # => IndexError: key not found
{:a => nil}[:b].foo # => NoMethodError

I think it makes sense in some situations as it can produce better backtrace. I would put it in guidelines with annotation "Consider using fetch instead of [](key)", not as a default.

sheerun commented 11 years ago

@jandudulski Of course not...

teamon commented 11 years ago

"Consider" sounds good :)

Ostrzy commented 11 years ago

:+1: for "Consider..."