· Jun 28, 2016 1m read

Calculate class or package length in sloc

Here's  a code snippet to calculate the length of a class or a package in lines of code:

ClassMethod ProjectLength(Mask As %String = "%Package%")
    Set count = 0
    Set sql =     "SELECT Name "_
                "FROM %Dictionary.ClassDefinition "_
                "WHERE NOT Name %STARTSWITH '%sqlcq' AND Name LIKE ? AND GeneratedBy IS NULL"
    Set rset = ##class(%SQL.Statement).%ExecDirect(, sql, Mask)
    While rset.%Next() {
        Set class = rset.%Get("Name")
        Do ##class(%Compiler.UDL.TextServices).GetTextAsArray(, class, .raw)
        Set lines = $ORDER(raw($CHAR(0)), -1)
        Write class, $JUSTIFY("", 40-$LENGTH(class)), $JUSTIFY(lines, 7), !
        Set count = count + lines
    Write "Total ", $JUSTIFY("",34), $JUSTIFY(count, 7)

All classes matching Mask would be displayed.

Use example:

USER>do ##class(Utils.CLS).ProjectLength("DSW%")
DSW.Installer                               169
DSW.InstallerData                           628
Total                                       797

Also available  on GitHub Gist.

Discussion (3)0
Log in or sign up to continue

It may be useful as one of the metrics related to the code quality/monitoring.

For example, my continuous integration system Cache GitHub CI tracks compile time for each commit, and if it suddenly grows, then the offending commit may be worth looking into.  But if we add one other metric - "lines of code added", then some of the offending commits may be removed based on a now determinable fact that a raise in compilation time is caused by a project size increase.

On the screenshot: compilation time (Length column) for some commits in a real-life project.


Other usage - find classes longer than, for example, 500 sloc and separate them into several classes.