For example, it is common in Ruby to:
![1, 2, 3].empty? => truein comparison to:
[1, 2, 3].any? => trueAsking for values is more straight forward than asking for not being empty. It removes the baggage of negation. Another example:
!"Ruby".blank? => truecan be refactored to:
"Ruby".present? => trueObject#present? is a monkey patch in Ruby on Rails, which is exactly the negation Object#blank? behind the scenes. But it is way more intentional.
Furthermore never do something like:
!11.even? => truebut instead:
11.odd? => trueThe last negation example is not that awkward apparently:
puts "Non zero" unless 1.zero? => "Non zero"but also can be refactored to the more optimistic:
puts "Non zero" if 1.nonzero? => "Non zero"Please note that the Numeric#nonzero? returns self if the number is not zero (which is truish), nil (equated with false) otherwise.
Preventing negations is also about the own API. Hiding negations behind the API is absolutely reasonable.
Stay positive!
Further articles of interest:
Supported by Ruby 2.1.1 and Ruby on Rails 4.1.8
Keine Kommentare:
Kommentar veröffentlichen