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:
!"Ruby".blank?
=> true
can be refactored to:
"Ruby".present?
=> 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:
!11.even?
=> true
but instead:
11.odd?
=> true
The 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