Skip to content

Instantly share code, notes, and snippets.

@HParker
Last active August 29, 2015 14:07
Show Gist options
  • Save HParker/24ec9bae7b41c571cc0f to your computer and use it in GitHub Desktop.
Save HParker/24ec9bae7b41c571cc0f to your computer and use it in GitHub Desktop.
Example Guard clause usage.

Good use of guard clauses

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.

Using guard clauses for Itempotency.

# 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment