我的代码包含未使用的变量和空的“catch”块。
在使用我的 IDE 和 SonarQube 进行静态代码分析时,被标记为
variable 'a' is never used
,并且有 empty 'catch' blocks
。
这些发现导致 SonarQube 得分较低。那么我可以做些什么来提高代码可读性并在不改变代码逻辑的情况下解决问题呢?
我的目标是增强代码的可读性并在 SonarQube 报告中取得更好的结果。
...
catch (StatementNotFoundException e) { } //Unused variable
...
_
)未命名变量和模式作为 Java 21 中的预览功能引入,现已根据 JEP 456 转变为 Java 22 中的最终确定功能。
用下划线字符
_
(低线,十进制 Unicode 代码点 95)表示,这些未命名的模式和变量增强了代码的清晰度和可维护性,同时减少了错误的可能性。
LinkedList<Integer> intLink = ...
while (intLink.size() >= i) {
var x = link.remove();
var _ = link.remove(); // Underscore character _
... new Coordinate(x) ...
}
ignore
)如果您有意使用空的 catch 块来忽略异常,那么遵循干净的编码实践仍然很重要。使用像
ignore
这样的变量名称而不是典型的描述性名称,向其他开发人员发出信号,表明该异常被有意忽略,从而减少混乱并使代码更具可读性。
这将删除 SonarQube 关于未使用变量的警告
...
catch (StatementNotFoundException ignore) { //variable ignore
//Nothing
}
...