Static Code Analysis

Notice: Sponsored Post by NDepend; But evaluated and tested by me.

 

In this post we are going to see why we should analyze our code and of course we'll see how to do this analysis.

Note that we are NOT going to see how to do a code review or check code when making a change, but we'll go a bit further and look at analysis from a static perspective.

For this, first we'll see what to focus on and how, and then we'll look at an application that can help us: ndepend.

 

1 - What is a static code analyzer?

These applications check that the code is correct, that there are no infinite loops in dependencies, if the code is too complex, but they DO NOT check functionality. For that, we have unit tests and integration tests.

 

2 - Why use a static code analyzer?

We must keep in mind that we are human, and as humans we all make mistakes, a never-ending loop can slip through a code review for all of us.

To avoid these situations (and the headache they can bring), we have applications that analyze code, called static code analyzers.

 

3 - Common uses for static code analyzers

Uniformity in code. With this type of application, we can define rules for naming, or for using tabs or spaces, for example, and if this rule is broken, we'll get an alert.

It might sound trivial, but using the same writing style throughout our code is important as it helps us read it better:

code uniformity

As we can see in the example, both classes are perfectly correct and work, but have different styles. Using static analysis applications helps maintain the same style at all times.

 

Code security analysis. Some static code analysis applications can help you identify when your code is not secure, either because you have an infinite loop or because your code is vulnerable to "cross-site scripting (XSS)" in the frontend or, for example, SQL injection in the backend.

This allows us to find bugs that would take much longer and be more expensive to find.

 

4 - When should we implement a code analyzer?

We should try to implement a code analyzer as soon as possible, because if we spend x months or years on a project and implement the analyzer at that moment, we could receive hundreds or thousands of alerts (depending on the number of developers and the size of the project) all at once. On the other hand, if we implement it from the start of the project's life, we will get alerts every now and then and fixing them won’t be a problem.

 

4.1 - Limitations of static code analyzers.

Of course, these types of applications have limitations, and the main one is that they don’t always understand the human approach.

The most common limitation is false positives. For example, the analyzer might alert you that certain code will fail because the variable has no value.

public double calcularIva(bool productoNacional, double precio)
{
    double iva;
    if(productoNacional)
    {
        iva = 0.21;
    }else
    {
        iva = 0.23;
    }

    return precio * iva;
}

In this example, an analyzer might warn that the variable iva has no value, even though it does. That’s what is called a false positive.

 

4.2 - Benefits of static code analyzers

There are many benefits, but I want to highlight three: speed, efficiency, and depth.

Speed and efficiency

When we perform code reviews, they often take some time, depending on the size of the change, and rarely do we check the rest of the codebase. I mean, we see that a method changed but we don’t manually check if this affects other services; for that, we have unit and integration tests.

The main reason we don’t analyze all possible paths is because it would take hours to do so. For that we have code analyzers, which are capable of evaluating all possible paths in seconds and, if they find a potential error, they report it very quickly.

Depth

By depth, I mean how complex or difficult a class within our code might be. Sometimes we have no choice but to make some methods very complex, due to a complicated algorithm, and that’s just how it is. But other times we overcomplicate things ourselves, adding dependencies or base classes unnecessarily.

This kind of application analyzes the code and can identify which parts are very complex and hard to understand. This is crucial for prioritization. For example, if a class is very complex, we could split it into several classes, or we can test it very thoroughly to avoid any potential bug so that no one ever has to change it.

The main problem with highly complex classes is that if there's any error or bug, it can take hours to understand and analyze the problem to find a fix.

 

5 - Applications to analyze code statically.

For this post I was going to use several applications, but it would get too long, so I’ll focus on just one, since they reached out to me after I tweeted about wanting to make a video about this topic: NDepend.

Other applications with similar features include codacy and sonarqube. Visual Studio Enterprise comes with a code analyzer, but I don’t have the enterprise version, so that's that.

 

Ndepend

Ndepend is software that performs static analysis on your code. For this introductory post, I’m going to show a couple of functionalities that I find very interesting.

Dependency Graph

Ndepend has a feature I love: it shows all dependencies and how they relate to each other so we can quickly see their relationships.

This graph is fully interactive so you can dig deeper and deeper into the projects.

dependency graph

Additionally, under the “metrics” section, you can see the number of references between different projects.

 

Code Depth

In our report, we have a section that indicates the depth or complexity of our code and how much time it would take to improve it.

depth

 

Issues and Rules

Finally, there is a section that shows us what code issues we have and which rules we are breaking.

issues and rules

We can see a list of these problems in the web report that opens.

issues ndepend website

I think these three sections are a good starting point when we start using a code analysis application.

Link to NDepend https://www.ndepend.com/

Conclusion

Using static code analyzers is very much recommended, especially in the work environment. For personal projects, maybe it's a lot, but for official company projects, if you don’t have one yet, you should push to implement one.

The fact that these applications tell us where we might have a system failure is crucial, since we can make mistakes when reviewing code.

 

This post was translated from Spanish. You can see the original one here.
If there is any problem you can add a comment bellow or contact me in the website's contact form

Uso del bloqueador de anuncios adblock

Hola!

Primero de todo bienvenido a la web de NetMentor donde podrás aprender programación en C# y .NET desde un nivel de principiante hasta más avanzado.


Yo entiendo que utilices un bloqueador de anuncios como AdBlock, Ublock o el propio navegador Brave. Pero te tengo que pedir por favor que desactives el bloqueador para esta web.


Intento personalmente no poner mucha publicidad, la justa para pagar el servidor y por supuesto que no sea intrusiva; Si pese a ello piensas que es intrusiva siempre me puedes escribir por privado o por Twitter a @NetMentorTW.


Si ya lo has desactivado, por favor recarga la página.


Un saludo y muchas gracias por tu colaboración

© copyright 2025 NetMentor | Todos los derechos reservados | RSS Feed

Buy me a coffee Invitame a un café