SonarQube 在以下代码中检测到问题“更改此条件,使其不会始终评估为‘假’;某些后续代码永远不会执行”。
public void SonarPleaseWhy(IList<string> texts)
{
var chain = new List<string>();
bool firstItemAdded = false;
bool otherItemAdded = false;
foreach (var text in texts)
{
if (!firstItemAdded && text.Length == 1)
{
chain.Add(text);
firstItemAdded = true;
}
else if (firstItemAdded && text.Length == 2)
{
chain.Add(text);
otherItemAdded = true;
}
else if (otherItemAdded && text.Length == 3)
{
Console.WriteLine(string.Join(',', chain));
chain.Clear();
firstItemAdded = false;
otherItemAdded = false;
}
else
{
chain.Clear();
firstItemAdded = false;
otherItemAdded = false;
}
}
}
这是 SonarQube 中的错误,还是我的代码中的一些真正问题?如果是后者,请帮助我,我不明白。
SonarQube 以红色突出显示
text.Length == 3
部分以及后续 elseif 块的主体。由于某种原因,第一个 elseif 块没有任何问题。
我尝试简化我的代码,这就是我如何达到这个(几乎)最小的可重现示例,但仍然看不到原因。
以下代码演示了可以输入
else if (otherItemAdded && text.Length == 3)
的主体,并且还评估了 && text.Length == 3
条件并且是必需的:
using System;
using System.Collections.Generic;
namespace Console1;
public static class Program
{
public static void Main()
{
string[] test = { "1", "22", "333", "1", "22", "4444" };
SonarPleaseWhy(test);
}
public static void SonarPleaseWhy(IList<string> texts)
{
bool firstItemAdded = false;
bool otherItemAdded = false;
foreach (var text in texts)
{
if (!firstItemAdded && text.Length == 1)
{
firstItemAdded = true;
}
else if (firstItemAdded && text.Length == 2)
{
otherItemAdded = true;
}
else if (otherItemAdded && text.Length == 3)
{
Console.WriteLine($"It entered the 'if' with text {text}");
firstItemAdded = false;
otherItemAdded = false;
}
else
{
firstItemAdded = false;
otherItemAdded = false;
}
}
}
}
(请注意,我已经从原始代码中删除了操作
chain
的代码,因为它在相关逻辑中不起作用。)
如果运行此命令,您将看到输出:
It entered the 'if' with text 333
现在注释掉条件的
&& text.Length == 3
部分并再次运行它。这次的输出是:
It entered the 'if' with text 333
It entered the 'if' with text 4444
这清楚地证明了我上面所主张的两点。
因此,如果 SonarQube 确实就这些事情警告您,那么这是误报(至少,仅基于您向我们展示的代码)。