Sonar常见问题修改
-
- 1 SonarLint简介与安装
- 2 SonarLint扫描以及IDEA中页面的名词解释
- 3 主要问题
-
- 1.String literals should not be duplicated
- 2.Deprecated elements should have both the annotation and the Javadoc tag
- 3.Generic exceptions should never be thrown
- 4.Method names should comply with a naming convention
- 5.Field names should comply with a naming convention
- 6.Unnecessary imports should be removed
- 7.Unnecessary imports should be removed
- 8.Raw types should not be used
- 9.Synchronized classes Vector, Hashtable, Stack and StringBuffer should not be used
- 10.”StandardCharsets” constants should be preferred
- 11.Synchronized classes Vector, Hashtable, Stack and StringBuffer should not be used
- 12.Synchronized classes Vector, Hashtable, Stack and StringBuffer should not be used
- 13.Local variables should not be declared and then immediately returned or thrown
- 14.Utility classes should not have public constructors
- 15.Methods should not have too many parameters
- 16.Nested blocks of code should not be left empty
- 17.Modifiers should be declared in the correct order
- 18.”@Deprecated” code should not be used
- 19.Track uses of “TODO” tags
- 20.Strings and Boxed types should be compared using “equals()”
- 21.Multiple variables should not be declared on the same line
- 22.”enum” fields should not be publicly mutable
- 23.”static” base class members should not be accessed via derived types
- 24.The diamond operator (“<>”) should be used
- 25.Collection.isEmpty() should be used to test for emptiness
- 26.”switch” statements should have at least 3 “case” clauses
- 27.Collapsible “if” statements should be merged
- 28.Unused assignments should be removed
- 29.Fields in a “Serializable” class should either be transient or serializable
- 30.”String#replace” should be preferred to “String#replaceAll”
- 31.Methods should not be empty
- 32.Unused “private” methods should be removed
- 33.Standard outputs should not be used directly to log anything
- 34.Empty arrays and collections should be returned instead of null
- 35.Standard outputs should not be used directly to log anything
- 36.Null pointers should not be dereferenced
- 37.Package declaration should match source file directory
- 38.Empty arrays and collections should be returned instead of null
- 38.”@Override” should be used on overriding and implementing methods
- 39.Cognitive Complexity of methods should not be too hig
- 40.XML parsers should not be vulnerable to XXE attacks
- 4 参考文章
1 SonarLint简介与安装
1.1 SonarLint简介
SonarLint是一个IDE插件,可帮助开发人员在编写代码时检测和修复质量问题。就像拼写检查器一样,SonarLint也会在提交代码之前对错误进行修正。开发人员可以直接从IDE市场获得它,然后它将在编码时(Java、JavaScript、PHP、Python和HTML)检测新的bug和质量问题。## 严重程度
1.2 SonarLint安装与配置
1.2.1 IDEA 插件在线安装
1.2.2 IDEA 插件离线安装
http://plugins.jetbrains.com/idea
搜索想要安装的插件,比如本文要安装的插件 SonarLint,在下面提示的下拉备选中,选择SonarLint跳转到插件页面.
在插件页面下面找到历史版本(Version History),找到想使用的版本,点击downLoad等待下载完成.
安装插件包
1.2.3 SonarLint General配置(如果有规定的sonarQube)
插件安装成功以后,打开插件配置界面,路径:File–Setting-Tools-SonarLint
弹窗窗口里,填写这个SonarLint的名称,我们使用的是本地sonarQube,选择的右边配置,输入sonarQube
IP和端口号.完成后点击Next.
1.2.3 SonarLint Project配置
- 选择下图中SonarLint Project Settings的菜单
- 勾选Bind project to SonarQube/SonarCloud
- 在Connection 右边下拉选择刚才配置的 sonar配置名称
- 配置Project key,可以点击Search in List,再弹出框里找到想使用的某个规则选择想使用的即可.
- 点击Apply使得配置生效保存
2 SonarLint扫描以及IDEA中页面的名词解释
2.1 SonarLint扫描
在需要扫描的文件或者文件夹右击->SonarLint->Analyze with SonarLint
2.2 IDEA中页面的名词解释
Current file:当前文件(展示当前文件存在的哪些问题,以及解决方法)
Rule:规则(告诉你问题的具体内容,并在最后告诉你如何解决这个问题)
Report:报告(鼠标移动到项目根目录,右键选择Ayalyze,选择Ayalyze with SonarLint,完成之后的结果显示,包含整个项目的所有文件的问题)
Locations:位置(告诉你,在哪个地方有问题,问题的重复位置)
Issues:问题 每个issue有五种等级
BLOCKER(致命):会影响应用程序的缺陷:内存泄漏,未关闭的JDBC连接…必须立刻修复的代码;
CRITICAL(关键):可能会影响应用程序的缺陷或者是安全性缺陷:空的catch块,sql注入,…必须立刻查看代码;
MAJOR(主要):可能会影响开发者效率的质量缺陷:未覆盖的代码,重复块,未使用的参数….
MINOR(微小):可能会影响开发者效率的质量缺陷:每行不能太长,“switch”语句应该至少有三个条件….
INFO(未知):既不是缺陷也不是质量问题,只是一个发现。
3 主要问题
1.String literals should not be duplicated
2.Deprecated elements should have both the annotation and the Javadoc tag
3.Generic exceptions should never be thrown
通用异常不应抛出 例如 Error Exception Throwable RuntimeException,修改为具体的或者自定义异常
在处理异常时,如果不往上抛的话,可以使用@SneakyThrows (编译后生成try catch)在本层处理。
4.Method names should comply with a naming convention
5.Field names should comply with a naming convention
6.Unnecessary imports should be removed
7.Unnecessary imports should be removed
8.Raw types should not be used
9.Synchronized classes Vector, Hashtable, Stack and StringBuffer should not be used
不应该使用同步类Vector, Hashtable, Stack和StringBuffer
10.“StandardCharsets” constants should be preferred
使用StandardCharsets.UTF_8 静态变量类型为charset 代替了HttpConstant.REQUEST_ENCODING这种静态变量类型为string的 符合java8规范
11.Synchronized classes Vector, Hashtable, Stack and StringBuffer should not be used
不应该使用同步类Vector, Hashtable, Stack和StringBuffer
12.Synchronized classes Vector, Hashtable, Stack and StringBuffer should not be used
不应该使用同步类Vector, Hashtable, Stack和StringBuffer
13.Local variables should not be declared and then immediately returned or thrown
14.Utility classes should not have public constructors
公用类的工具类不应该有公共的构造函数,公用的工具类是静态成员的集合,并不意味这要实例化,当工具类不定义构造函数,Java会自动向不定义构造函数的每个类添加公共的构造函数,和公用类不应该具有公共的构造函数冲突了,因此我们需要手动添加该公用工具类的构造函数。
/**
* @Classname AdentUtil
* @Description 中介工具类
* @Version 1.0.0
* @Date 2023/3/27 13:46
* @Created by admin
*/
public class AdentDataTransferUtil {
/**
* 构造下载报文
* @param adentResultFileGeneralRespDto
* @return
*/
public static UniteAdentResultFileRespDto getUniteAdentResultFileRespDto(AdentResultFileGeneralRespDto adentResultFileGeneralRespDto) {
UniteAdentResultFileRespDto uniteAdentResultFileRespDto=null;
if (adentResultFileGeneralRespDto != null) {
uniteAdentResultFileRespDto=new UniteAdentResultFileRespDto();
uniteAdentResultFileRespDto.setFileUnid(adentResultFileGeneralRespDto.getUnid());
uniteAdentResultFileRespDto.setFileName(adentResultFileGeneralRespDto.getName());
uniteAdentResultFileRespDto.setDownlaodUrl(adentResultFileGeneralRespDto.getDownloadUrl());
}
return uniteAdentResultFileRespDto;
}
private AdentDataTransferUtil() {
throw new IllegalStateException("Utility class");
}
}
15.Methods should not have too many parameters
用Spring的@RequestMapping(以及相关的快捷注释,如@GetRequest)或@JsonCreator注释的方法可能有很多参数,封装是可能的。因此,这些方法将被忽略。
16.Nested blocks of code should not be left empty
嵌套的代码块不应该留空
删除嵌套的空的代码块
17.Modifiers should be declared in the correct order
18.“@Deprecated” code should not be used
不能使用 或者不建议使用 @Deprecated 修饰的代码
例:import org.springframework.util.StringUtils; 引入了spring的包,但是它的StringUtils。isEmpty()不被建议使用,改用其他的的包 比如 org.apache.commons.lang3.StringUtils
19.Track uses of “TODO” tags
20.Strings and Boxed types should be compared using “equals()”
if(entry.getCode()==condition){}
修改为if(entry.getCode() != null && entry.equals(condition)){}
21.Multiple variables should not be declared on the same line
22.“enum” fields should not be publicly mutable
23.“static” base class members should not be accessed via derived types
原代码:JSONArray licenseArr = JSONArray.parseArray(licenseData);
修改后 JSONArray licenseArr = JSON.parseArray(licenseData);
为了代码清晰起见,永远不要使用子类的名称访问父类的静态成员。这样做会造成混淆,并且可能会导致存在两个不同的静态成员的错觉。直接使用父类访问父类静态成员。
24.The diamond operator (“<>”) should be used
应该使用菱形操作符(“<>”)
Java 7引入了diamond操作符(<>)来减少泛型代码的冗长。例如,不必在列表的声明和构造函数中声明列表的类型,现在可以使用<>简化构造函数声明,编译器将推断类型
25.Collection.isEmpty() should be used to test for emptiness
应该使用Collection.isEmpty()来测试是否为空
26.“switch” statements should have at least 3 “case” clauses
27.Collapsible “if” statements should be merged
Noncompliant Code Example
if (file != null) {
if (file.isFile() || file.isDirectory()) {
/* ... */
}
}
Compliant Solution
if (file != null && isFileOrDirectory(file)) {
/* ... */
}
private static boolean isFileOrDirectory(File file) {
return file.isFile() || file.isDirectory();
}
28.Unused assignments should be removed
未使用的作业应该被删除
当局部变量被赋值后,后续指令不会读取该值时,就会发生死存储。计算或检索一个值,然后重写或丢弃它,可能表明代码中存在严重错误。即使这不是一个错误,它最多也是一种资源浪费。因此,应使用所有计算值。
29.Fields in a “Serializable” class should either be transient or serializable
“Serializable”类中的字段应该是瞬态的或者是可序列化的
当一个类实现了序列化接口 Serializable,意味着他可以可以序列化和反序列,当这个类里面的属性B没有实现 序列化接口 Serializable,意味着B不能序列化和反序列化,那么也就是类中的属性B不能序列化,sonar会报错。
1.为这个类B实现序列化接口 implement serializable
2.在属性B前面加上 transient 关键字 — private transient B b;
transient 对于transient 修饰的成员变量,在类的实例对象的序列化处理过程中会被忽略。
30.“String#replace” should be preferred to “String#replaceAll”
“String#replace“应该优先于”String#replaceAll”
31.Methods should not be empty
private Assert() {
throw new IllegalStateException("Assert class");
}
32.Unused “private” methods should be removed
应该删除未使用的“私有”方法
33.Standard outputs should not be used directly to log anything
34.Empty arrays and collections should be returned instead of null
Noncompliant Code Example
public static List<Result> getAllResults() {
return null; // Noncompliant
}
public static Result[] getResults() {
return null; // Noncompliant
}
public static Map<String, Object> getValues() {
return null; // Noncompliant
}
public static void main(String[] args) {
Result[] results = getResults();
if (results != null) { // Nullity test required to prevent NPE
for (Result result: results) {
/* ... */
}
}
List<Result> allResults = getAllResults();
if (allResults != null) { // Nullity test required to prevent NPE
for (Result result: allResults) {
/* ... */
}
}
Map<String, Object> values = getValues();
if (values != null) { // Nullity test required to prevent NPE
values.forEach((k, v) -> doSomething(k, v));
}
}
Compliant Solution
public static List<Result> getAllResults() {
return Collections.emptyList(); // Compliant
}
public static Result[] getResults() {
return new Result[0]; // Compliant
}
public static Map<String, Object> getValues() {
return Collections.emptyMap(); // Compliant
}
public static void main(String[] args) {
for (Result result: getAllResults()) {
/* ... */
}
for (Result result: getResults()) {
/* ... */
}
getValues().forEach((k, v) -> doSomething(k, v));
}
35.Standard outputs should not be used directly to log anything
36.Null pointers should not be dereferenced
空指针不应该被解引用
37.Package declaration should match source file directory
38.Empty arrays and collections should be returned instead of null
public static List<Result> getAllResults() {
return Collections.emptyList(); // Compliant
}
public static Result[] getResults() {
return new Result[0]; // Compliant
}
public static Map<String, Object> getValues() {
return Collections.emptyMap(); // Compliant
}
public static void main(String[] args) {
for (Result result: getAllResults()) {
/* ... */
}
for (Result result: getResults()) {
/* ... */
}
getValues().forEach((k, v) -> doSomething(k, v));
}
38.“@Override” should be used on overriding and implementing methods
39.Cognitive Complexity of methods should not be too hig
40.XML parsers should not be vulnerable to XXE attacks
4 参考文章
Sonar代码规则之TOP30详解
在IDEA上配置SonarLint以及代码质量分析报告模板
@SneakyThrows注解
Sonar问题汇总
https://rules.sonarsource.com/
原文地址:https://blog.csdn.net/qq_43238568/article/details/130193304
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_37200.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!