声纳严重违规 - 以前取消引用的Nullcheck值 [英] Sonar critical violation - Nullcheck of value previously dereferenced

查看:1005
本文介绍了声纳严重违规 - 以前取消引用的Nullcheck值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我在我的一个测试类中的下面一段代码,Sonar抛出了一个严重的违规行为 - 正确性 - 以前取消引用的价值的Nullcheck

For the below piece of code I have in one of my test classes, Sonar throws me a critical violation - Correctness - Nullcheck of value previously dereferenced

 if (testLst != null && !testLst.isEmpty()) {
        for (Test test : testLst) {
            if (test.getName().equalsIgnoreCase("TEST")) {
            // do blah
            }

有人可以关于我在这里做错了什么呢?

Can someone throw some light on this on what am I doing wrong here?

编辑:这里的答案之一建议这是因为我之前可以访问变量,所以空检查是多余的。但事实并非如此。这是我的空检查之前的代码行。

One of the answers here suggested this is because I could have accessed the variable before, and so the null check is redundant. That's not true though. Here is the line of code before my null check.

 testLst = myTest.getValues(); //I am basically populating the array by doing a get, but I am not accessing the list itself by doing a get on it directly - like testLst.get()
 if (testLst != null && !testLst.isEmpty()) {
            for (Test test : testLst) {
                if (test.getName().equalsIgnoreCase("TEST")) {
                // do blah
                }


推荐答案

当您检查时会显示此消息如果变量的值为null(在本例中为 testLst ),则之前已经访问过该变量。不需要空检查,因为如果值为null,则抛出 NullPointerException

This message is shown when you're checking if a variable's value is null (in this case testLst) whereas you already accessed the variable before. The null check is not needed since if the value was null, a NullPointerException would have been thrown.

示例:

testLst.remove(something);
if (testLst != null && !testLst.isEmpty()) {
    for (Test test : testLst) {
       if (test.getName().equalsIgnoreCase("TEST")) {
        // do blah
        }

支票 testLst!= null 是多余的,因为当程序到达 if 语句时, testLst 不能为null,否则前面的语句 testLst.remove(某事物)会抛出 NullPointerException 。在这种情况下,您应该在访问 testLst 之前,在 为空的地方放置空检查:

The check testLst != null is redundant since at the time the program reaches the if statement, testLst cannot be null, otherwise the previous statement testLst.remove(something) would have thrown a NullPointerException. In this case, you should place the null check before accessing testLst, in a place where it can be null:

if(testLst != null) {
   testLst.remove(something);
   if (!testLst.isEmpty()) {
       for (Test test : testLst) {
          if (test.getName().equalsIgnoreCase("TEST")) {
           // do blah
          }

这篇关于声纳严重违规 - 以前取消引用的Nullcheck值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆