Avdi Grimm's book has a section on guard classuses showing a refactor from
# From
def log_reading(reading_or_readings)
readings = Array(reading_or_readings)
readings.each do |reading|
puts "[Reading] %3.2f" % reading.to_f
end
end
# To
def log_reading(reading_or_readings)
if @quiet then return end
readings = Array(reading_or_readings)
readings.each do |reading|
puts "[Reading] %3.2f" % reading.to_f
end
end
This shows an example of silencing logging with a guard clause.
I think that this applies other places as well. This avoids the trailing if
for a fairly likely case while still allowing a guard clause to prevent wrapping a while method in an if/unless
statement.
# bad
def itempotent_save
if no_change
self
else
self.save
# other things I do when I save.
# ...
end
end
# better
def itempotent_save
if no_change then return self end
self.save
# other things I do when I save.
# ...
end
I think this is a more readable solution that avoids the trailing if and provides a guard clause for trapping unwanted cases. There is an arguement to be made for not calling methods when you don't want them to do anything. however, when the correct behavior is to do nothing, that method should do nothing.