The suffix-style if and unless can also be useful for "protective sentences" in the form:
return if ... return unless ...
Here is an example:
# suffix-style def save return false if invalid?
Versus:
# indented style def save if valid? # go for it true else false end end
In the second example, the entire implementation of the method must be indented by validation valid? , and we need an additional else clause. With suffix type invalid? check invalid? is considered a boundary case that we process and then exit the system, and the rest of the method does not require indentation or the else clause.
This is sometimes called a โdefensive offerโ and is recommended in the Ruby style guide.
source share