Flog and to_proc_normal

Posted on by Admin

Using metrics like flog can be immensely helpful for cleaning up code. However, metrics are fallible, and flog is no exception.

During a session of some serious code refactoring, flog was returning high scores on a couple of methods that appeared to be relatively clean, and the main culprit for the scores was something called to_proc_normal.

Consider this example. We have a Test class and Fruit class. Within the Test class are the following methods:

Both methods return an array containing the names of fruits associated to the Test class. They are, functionally, extremely similar. So how do they match up in flog?

Test#fruit_names_1 has a poor score in comparison to its counterpart thanks to this elusive to_proc_normal. We run some benchmarks—with 100,000 calls to each method on an instance of Test—to see if there is a difference in execution time:

Benchmarking speaks for itself. While the first method has a flog score that may imply a some unwieldy code with lengthier execution time, it generally runs faster than the second anyway. Of course, flog is still awesome, and it's one of the more helpful ways to quickly identify "code smells" (like large or overly-complicated methods) in a ruby project.

Note:

These metrics were originally measured on ruby version 1.8.7p72. After upgrading to version 1.9.1p378, the flog scores remained the same, but the benchmarks consistently favored the second method. And the performance difference itself induced a double-take:

 
comments powered by Disqus