Sunday, April 28, 2013

Flay, a gem to help improve the maintainability of your code

Recently I read a post where the author listed the must have gems for rails development. Being an avid watcher of Railscasts I knew many of them however one, flay, caught my attention. It comes out of the Seattle Ruby group which also brought us flog.

Flay is along the same lines as Flog; it analyzes your code looking for issues. Rather than looking for tortured code though it is looking for similar or duplicate code blocks. You install with `gem install flay` and then run it against your files, e.g.:

flay ./app/models/*.rb

A report is generated of the suspect areas like this:

macscott:test-project scottshea$ flay ./app/models/*.rb
Total score (lower is better) = 1666

1) Similar code found in :call (mass = 170)
  ./app/models/level.rb:8
  ./app/models/level.rb:9
  ./app/models/level.rb:10
  ./app/models/level.rb:11
  ./app/models/level.rb:15
  ./app/models/level.rb:17
  ./app/models/level.rb:19
  ./app/models/level.rb:20
  ./app/models/level.rb:22
  ./app/models/level.rb:23

2) Similar code found in :defs (mass = 154)
  ./app/models/item_step.rb:260
  ./app/models/response.rb:195

3) Similar code found in :defs (mass = 138)
  ./app/models/feedback.rb:62
  ./app/models/hint.rb:54
  ./app/models/subtitle.rb:51

4) Similar code found in :call (mass = 136)
  ./app/models/level.rb:12
  ./app/models/level.rb:13
  ./app/models/level.rb:14
  ./app/models/level.rb:16
  ./app/models/level.rb:18
  ./app/models/level.rb:21
  ./app/models/level.rb:24
  ./app/models/level.rb:25

5) IDENTICAL code found in :defn (mass*2 = 128)
  ./app/models/report_generator.rb:7
  ./app/models/summary_report_generator.rb:7

6) IDENTICAL code found in :defn (mass*2 = 120)
  ./app/models/image.rb:17
  ./app/models/sharded_image.rb:23

[truncated]

The total app score of 1666 can be viewed in its individual components showing areas that provide the most bang for the buck. For experienced developers operating on their own or in a small team Flay may be unnecessary. However, on larger projects (as the one I ran it on) or those with beginner or intermediate programmers it can help increase the maintainability of your codebase.

I am not sure where the 1666 would rank on the overall chart (is that really bad? representative?) but the 'lower is better' advice holds true. This Stackoverflow question offers some interpretation of the score but really the best advice is "don't let it get higher!"

No comments:

Post a Comment