LoginSignup
4
7

More than 3 years have passed since last update.

Cognitive Complexity メモ

Posted at

Cognitive Complexity というコードの理解しやすさを測る指標がある。

提唱されているドキュメント
https://www.sonarsource.com/docs/CognitiveComplexity.pdf

日本語での解説
https://qiita.com/suzuki_sh/items/824c36b8d53dd2f1efcb

似た指標としては、Cyclomatic Complexity(循環的複雑度)があるが、こちらは実行経路の数を算出しているので、コードの理解しやすさと必ずしも一致するわけではない。

上記、qiita 記事にある switch 文の解説が分かりやすい。

Code Climate CLI によるチェック

手軽に手元のコードの Cognitive Complexity をチェックしたければ、Code Climate CLI の Docker イメージを使うと楽。

計測したいコードのディレクトリに移動して、下記コマンドを実行すれば良い。

$ docker run --rm --env CODECLIMATE_CODE=`pwd` --env CODECLIMATE_DEBUG=1 -v `pwd`:/code -v /var/run/docker.sock:/var/run/docker.sock -v /tmp/cc:/tmp/cc codeclimate/codeclimate analyze

== Foo.php (1 issue) ==
56-88: Function `doSomething1` has a Cognitive Complexity of 8 (exceeds 5 allowed). Consider refactoring. [structure]

== Bar.php (1 issue) ==
60-90: Function `doSomething2` has a Cognitive Complexity of 6 (exceeds 5 allowed). Consider refactoring. [structure]

Analysis complete! Found 2 issues.

初回は、いくつかの Docker イメージを pull するので遅い。CODECLIMATE_DEBUG=1 は付けなくても良いが、付けておいたほうが実行している様子が見えるので良い。

デフォルト設定では、Cognitive Complexity が 6 以上のものが検出されるので、上記実行結果では、2 つのメソッドがリファクタリング候補として検出されている。

Code Climate CLI は、Cognitive Complexity 以外にも様々な指標を計測してくれるので詳細は下記で。

参考

Cognitive Complexity を計測するツールがいくつかある。

Go

PHP

C#

4
7
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
4
7