No matter if you are Rails quality assurance engineer in huge development company, or single developer that wants to make his code as good as possible, you should periodically run static code analysis tools. While choices are very wide for Ruby 1.8 users, we, who switched to most recent version of 1.9.2, don’t have much choice yet. And here comes metric_abc.
One of commonly used code complexity metrics is ABC metric. What it does, is counting number of Assignments, Branches and Conditions in methods you write. You should write small, easy to read, understand and test methods. Such code is short, precise, don’t call a million of external functions and is easy to test. ABC metric is higher for bad code, lower for good one.
To install metric_abc in your Ruby 1.9 environment you simply need to:
$ sudo gem install metric_abc
If you have your $PATH configured properly, you should have “metric_abc” command available. This command takes a list of files to analyse as only parameters so far. Here’s example usage that was performed during Rails project quality assurance process:
$ cd ~/myapp/app $ metric_abc `find . -iname *.rb` ./models/content_processor.rb > ContentProcessor > process_content: 10 ./helpers/paths_helper.rb > PathsHelper > recognize_path: 7 ./controllers/admin/generic_actions.rb > GenericActions > destroy: 7 ./uploaders/picture_uploader.rb > PictureUploader > store_dir: 5
Output gives you file name, module/class names and function name, followed by ABC score, ordered by score descending. So on top you can see most complex methods and on bottom less complex ones.
What are good scores and what are bad ones? It really depends on context, type of program and your coding style. For normal Rails projects, probably anything above 20 points could be re-factored to be nicer and more readable, but it’s really up to you to decide. metric_abc is here only to point you to possible problems with your code, it’s not super smart AI with coding skills.
Post by Hubert Łępicki
Hubert is partner at AmberBit. Rails, Elixir and functional programming are his areas of expertise.