code quailty metrics demystified
TRANSCRIPT
Code Quality Metrics Demystified@JeroenResoort @jdriven_nl
What are metrics?
Why use metrics?
Why use metrics?To measure software quality
What is software quality?
Why use metrics?To measure and improve software maintainability attributes:
● Analysability
● Changeability
● Stability
● Testability
How to collect metrics?
How to use / collect metrics?IDE
CheckStyle
SonarQube
How to collect metrics?docker run -d --name sonarqube -p 9000:9000 -p 9092:9092 sonarqube
mvn sonar:sonar
Volume
VolumeFiles / Classes
Lines
Lines of code
LoC per file
LoC per method
Volumepublic int sum(int a, int b) {
return a + b;
}
Volumepublic int sumToo( int a
, int b )
{
int result = a + b;
return result;
}
Volumepublic List<Integer> calculate(List<Integer> numbers) {
return numbers.stream().map(i -> i * i).filter(i -> i % 2 == 0).collect(Collectors.toList());
}
Volumepublic List<Integer> calculateFormatted(List<Integer> numbers) {
return numbers.stream().
map(i -> i * i).
filter(i -> i % 2 == 0).
collect(Collectors.toList());
}
Volumeimport java.util.List;
import java.util.ArrayList;
import java.util.Set;
import java.util.HashSet;
Volumeimport java.util.*;
Cyclomatic Complexity
Cyclomatic ComplexityMcCabe, 1976
Control flow graph
Linearly independent paths
Cyclomatic Complexity
Cyclomatic ComplexityThe complexity M is defined as
M = E − N + 2P,
where
E = the number of edges of the graph.
N = the number of nodes of the graph.
P = the number of connected components.
Cyclomatic ComplexityAlternative formula
M = E − N + P
After connecting exit point to entry point
Cyclomatic Complexity
Cyclomatic Complexitypublic int sum(int a, int b) {
return a + b;
}
Cyclomatic Complexitypublic int sum(int[] amounts) {
int result = 0;
for (int i = 0; i < amounts.length; i++) {
result += amounts[i];
}
return result;
}
Cyclomatic Complexitypublic boolean checkWithdrawal(Account account, int amount) {
boolean result = false;if (account.getBalance() >= amount) {
result = true;}if (account.isLocked()) {
result = false;}return result;
}
Cyclomatic Complexitypublic boolean checkWithdrawal(Account acc, int amount) {
if (!acc.isLocked() && acc.getBalance() >= amount) {
return true;
}
return false;
}
Cyclomatic ComplexityComplexity per class
Complexity per method
Fan in / Fan out
Fan in / Fan outFan in: number of classes referencing you
Fan out: number classes you are referencing
Package Entanglement
Package Entanglement
Duplication
DuplicationHow to check?
Per line vs multiple lines?
Exact match or not?
Unit Test coverage
Unit Test coverageBad examples
Unit Test coverageAre your unit tests actually testing the right things?
Mutation tests!
ConclusionA lot of metrics available
Understand what they mean
Don’t use metrics as KPIs!
Questions?
Code Quailty Metrics Demystified@JeroenResoort @jdriven_nl