Guard Clauses
Methods can become difficult to read when nested conditionals are introduced. Even in simple examples like the one below, determining under what conditions the method gets executed is slightly ambiguous. The sideways pyramid shape that the code is taking on is adding unnecessary burden to your eyes as you scan the screen.
class Person < ActiveRecord::Base def determine_city if zipcode.present? if zipcode.to_city.present? update(city: zipcode.to_city) end end end end
Guard clauses can fix this problem by eliminating nested conditionals. A guard clause simply return
s from the method when a given condition is met:
class Person < ActiveRecord::Base def determine_city return if zipcode.blank? return if zipcode.to_city.blank? update(city: zipcode.to_city) end end
This feels like a much cleaner way to validate inputs to a method. It is much easier to read and determine under what conditions that the method would be run.