Class: RuboCop::Cop::Guardrails::NoGuardClauses

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/guardrails/no_guard_clauses.rb

Overview

Discourages guard clauses (conditional early returns).

Guard clauses obscure the actual flow of a method. In short methods, prefer a conditional expression. In longer methods, one guard clause is tolerated at the very beginning.

The ‘MinMethodLength` option (default: 10) controls the threshold. Methods longer than this are allowed one leading guard clause.

Examples:

# bad
def something
  return if thing.nil?

  thing.do_something
end

# good — use a conditional expression
def something
  thing.do_something if thing.present?
end

# good — use an expanded conditional
def something
  unless thing.nil?
    thing.do_something
  end
end

# good — long method, one guard clause at the top
def something
  return unless valid?

  step_one
  step_two
  step_three
  # ...
end

Constant Summary collapse

MSG =
'Avoid guard clauses. Prefer a conditional expression.'

Instance Method Summary collapse

Instance Method Details

#on_def(node) ⇒ Object Also known as: on_defs



48
49
50
51
52
53
# File 'lib/rubocop/cop/guardrails/no_guard_clauses.rb', line 48

def on_def(node)
  guards = leading_guard_clauses(node)
  allowed = method_length(node) > min_method_length ? 1 : 0

  guards.drop(allowed).each { |guard| add_offense(guard) }
end