Sonntag, 1. März 2015

Prevent negations in Ruby!

Programming is about the communication between human being and the machine. So it is all about readable codes. That said, there are still some basic coding techniques widely used, which are less readable. Negation is one of them.
For example, it is common in Ruby to:
![1, 2, 3].empty?
=> true
in comparison to:
[1, 2, 3].any?
=> true
Asking for values is more straight forward than asking for not being empty. It removes the baggage of negation. Another example:
=> true
can be refactored to:
=> true
Object#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:
=> true
but instead:
=> true
The last negation example is not that awkward apparently:
puts "Non zero" unless
=> "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