LoginSignup
64
39

More than 5 years have passed since last update.

Rubocop の Metrics AbcSize チェックについて

Last updated at Posted at 2015-05-11

はじめに

rubocop を導入しました。
大抵のアラートは -a, --auto-correct オプションを指定することで、自動でなおしてくれます。

自動でなおらない箇所も、内容をみてサクサク潰せるのですが、Metrics AbcSize チェック は一筋縄ではいかないやっかいなものだったので、なおしていく流れをまとめます。

Rubocop の Metrics AbcSize チェックについて

そもそも、Metrics AbcSize チェックとは何?ということで、以下の定義となります。

ABC is strictly a software size metric, although it has often been misconstrued as a complexity metric.

Size is computed by counting the number of assignments, branches and conditions for a section of code. The counting rules in the original C++ Report article were specifically for the C, C++ and Java languages, and defined as:

    Assignment -- an explicit transfer of data into a variable, e.g. = *= /= %= += <<= >>= &= |= ^= >>>= ++ --
    Branch -- an explicit forward program branch out of scope -- a function call, class method call, or new operator
    Condition -- a logical/Boolean test, == != <= >= < > else case default try catch ? and unary conditionals.

A scalar ABC size value (or "aggregate magnitude") is computed as:

       |ABC| = sqrt((A*A)+(B*B)+(C*C))

要するに、「代入少なく、関数呼び出し少なく、制御構文少なく」ということです。

これは、今まで開発者が感じていたプログラムの 匂い を定量的に判断してくれるものですね。

Metrics AbcSize チェックのアラートを改修

1. AbcSize チェック以外のアラートをなおす

以下のような別のアラートを解消しているうちに AbcSize チェックもパスするように改善されるようになります。

  • LineLength チェック: 1行の長さ
  • MethodLength チェック: 1メソッドの大きさ
  • CyclomaticComplexity チェック: 制御構文の数

2. リファクタリング

メイン作業です。

一時変数の導入やメソッドの抽出などしながら、メソッドを小さくしていきます。

リファクタリングに関するテクニックは色々あるので他サイトを参考にしてください。

3. AbcSize チェックの条件みなおし

最後の手段。

デフォルトの AbcSize チェックの基準値は 15 です。
プロジェクトの状況にあわせて .rubocop.yml で基準値を調整します。(甘えですね)

Metrics/AbcSize:
  Max: 20

最後に

rubocop を導入した意味を考え、本末転倒にならないようにしましょう。

あくまで、システムの品質を向上させるための1ツールです。アラートが出ないようにすることが主ではありません。

参考

64
39
0

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
64
39