Are there code metrics that will cover the variable scope

In an attempt to get a general overview of how difficult it is to keep some legacy C ++ and C # code, and the risk of introducing errors into it, it has been suggested that it would be useful to measure how wide or narrow the variables change. The code uses many globals or large-scale variables where local ones will be better. A common occurrence is the discovery that these variables are used for 2 or 3 lines of code with several levels of coverage from where they are declared.

I know that static code analysis tools usually try to quantify connectivity and cohesion, but is there something more specific about the scope of variables / data?

+8
java c ++ c # metrics static-analysis
source share
3 answers

Yes, this is the standard static analysis technique. This is called variability analysis. In this book, an implementation example does such an analysis.

From the Wikipedia article about this:

In compiler theory, a living variable analysis (or simply survivability analysis) is a classic data flow analysis performed by compilers to compute for each program point variables that can potentially be read before their next record, that is, variables that live in the output of each program points.

Simple: a variable is live if it contains a value that may be needed in the future.

+2
source share

I will focus on local variables in OO languages ​​(Java, C #, C ++). I can come up with a series of measures regarding the scope of a local variable.

Local Variable Area Size
- the number of operators available for the local variable. This should not be too large, as it indicates a method too long. However, counting a method operator may be more appropriate for this.

Available value of a local variable
- the number of available local variables for each method operator. It should not be more than 3, as it makes the choice which local variable is used in the expression more difficult.

Local density using variables
represents the percentage of statements accessing a local variable and statements where a local variable is available. Low values ​​indicate that the method is not very coherent.

Coherent modification of local variable calculations
- the number of modifications of local variables within the same block. This indicates that several local variables belong to each other. Therefore, they must create their own object, thereby increasing consistency.

0
source share

You can try CppDepend , and the CQLinq query language can detect some global variables used by only one method or, possibly, one class.

from f in Fields where f.IsGlobal && f.MethodsUsingMe.Count()==1 select f 
0
source share

All Articles