Code Metrics¶
Code metrics are a form of static analysis that aim to give an indication of the quality of your code. Various metrics have been developed over the years, and Sourcery uses a number of them.
In Sourcery, code metrics are shown in the IDE when hovering over a function name. These aim to help you understand the quality of your code and how you can improve it.
Remember that metrics are not the be-all and end-all of code quality, but they are a useful indicator.
A function with a good quality score may still not be great code, but a function with a low score is very likely to be poor code.
Complexity¶
The complexity metric is a measure of how difficult your code is to read and understand. It is based on these principles:
- Each break in the linear flow of the code makes it harder to understand
- When these flow-breaking structures are nested they are even harder to understand
Flow-breaking structures are things like conditionals, loops and complex series of logical operators.
Full details of how this metric is calculated are contained in the Cognitive Complexity: A new way of measuring understandability white paper by G. Ann Campbell of SonarSource.
Improving complexity scores¶
An important way to reduce the complexity of your code is to reduce the amount of nesting.
- Merging nested if conditions is a quick win.
- Introducing guard clauses can also be useful, if there are conditions that are checked at the beginning of your method.
- Extracting out chunks of related code into their own methods can also keep nesting to a minimum.
Method Length¶
The method length metric is a measure of how long each method is on average. It is based on the number of nodes in the method's Abstract Syntax Tree.
It is better for methods to be concise and to do one thing, so this metric penalises overly long methods.
Working Memory¶
The working memory metric is a measure of the number of variables that need to be kept in your working memory as you read through the code.
See here for a full description of the metric.
Improving poor Working Memory scores¶
The primary way to improve code that scores poorly on this metric is to break up large functions into smaller ones. You can take a look at our blog post here for a practical example of how to do this.
Other ways are to extract complex conditional tests into variables or functions.
Quality Score¶
The quality score we show is a percentage score for code quality, with 100 being the highest score. It is a calibrated and scaled blend of the complexity, length and working memory metrics.