22
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RuboCop | Style/CyclomaticComplexity

Posted at

RuboCop | Style/CyclomaticComplexity

概要

RuboCopの「Style/CyclomaticComplexity」警告について。

Rubyの循環的複雑度をチェックします。
RuboCopのソースを確認すると、

DECISION_POINT_NODES = [:if, :while, :until, :for, :rescue, :when, :and, :or]
# :
# : 略
# :
on_node(DECISION_POINT_NODES, node) { complexity += 1 }

[:if, :while, :until, :for, :rescue, :when, :and, :or] をキーとして、循環的複雑度を加算しているようです。

※ソース全体が気になる方は以下を参照
https://github.com/bbatsov/rubocop/blob/master/lib/rubocop/cop/style/cyclomatic_complexity.rb

設定値

Maxに値を設定します。
デフォルトは6です。

CyclomaticComplexity

各設定値での検証結果をまとめます。

検証プログラム

cyclomatic_complexity.rb

def hoge(msg)
  return 1 if msg.empty?   # => if 1
  return 2 unless msg.nil? # => unless 2
  case msg
  when 'hoge' then 'hoge'  # => when 3
  when 'hige' then 'hige'  # => when 4
  when 'hege' then 'hege'  # => when 5
  else 'other'             # => else 6
  end
rescue                     # => rescue 7
  raise StandardError, 'error'
end

実行結果 デフォルト の場合

.rubocop.yml

※明示的に設定しているが、デフォルト値なので何も設定しなくてもよい

CyclomaticComplexity:
  Max: 6
$ rubocop
Inspecting 1 file
C

Offenses:

cyclomatic_complexity.rb:1:1: C: Cyclomatic complexity for hoge is too high. [7/6]
def hoge(msg)
^^^

1 file inspected, 1 offense detected

実行結果 Max を 7 に変更した場合

.rubocop.yml

CyclomaticComplexity:
  Max: 7
$ rubocop
Inspecting 1 file
.

1 file inspected, no offenses detected
22
13
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?