Version 3 of Counting comments in a source

Updated 2006-01-15 22:23:32

In my humble opinion, quality control begins at the simple fact of evaluate how much comment lines proliferate in any program. Here is a simple GUI to perform this tasks. It prints :

  • The total line count
  • The comment line count
  • How many comment lines there are against 100 lines of code

-- Sarnold 13/01/2006

So, do you believe "more comments == high quality" or "fewer comments == high quality"? One can effectively argue both cases.

The real metric, IMO, is not how many comments, but how many useful comments. Sadly, there's no tool to give us that metric.


 proc LinesNComments {file} {
        set fd [open $file r]
        set comments 0
        set lines 0
        while {![eof $fd]} {
            gets $fd line
                  set line [string trimleft [string trimleft $line \t]]
                  if {[string equal $line ""]} {
                      continue
                  }
                  # skip comments lines with no words
                  if {[string index $line 0]=="#"} {
                if {![regexp {^\b*#+[a-zA-Z0-9]*} $line]} {continue}
                      incr comments
                  }
            incr lines
        }
        close $fd
        return [list $lines $comments]
 }
 wm title . "Check the use of comments in Tcl files"
 button .inspect -command Inspect -text "Inspect file"
 button .quit    -command exit    -text "Quit"
 pack .inspect .quit

 proc Inspect {} {
        set file [tk_getOpenFile]
        if {![file exists $file]} {tk_messageBox -message "No such file: $file";return}
        foreach {lines comments} [LinesNComments $file] {}
        set percentage [expr {double($comments)*100/double($lines-$comments)}]
        tk_messageBox -message "file $file : $lines lines and $comments comments lines,
 for 100 lines of code there are $percentage lines of comments"
 }

Category File