SonarLint 代码扫描错误提示总结
这篇文章主要介绍了使用sorna扫描代码出现的错误提示总结。
- Avoid long parameter lists.
方法参数过多,最多允许5个
- Missing a Javadoc comment.
需要注释
- Expected @param tag for ‘area’.
需要注释
- Expected @return tag.
需要注释
- Expected @throws tag for ‘Exception’.
需要注释
- Unused @param tag for ‘licenseInfoMap’.
修改注释
- Line is longer than 160 characters (found 162).
每一行代码不得超过160个字符,需要分行
- Add a private constructor to hide the implicit public one.
常量类和工具类需要一个私有的构造器,同时将该类定义为final,不可继承
- Variables that are final and static should be all capitals, ‘logger’ is not all capitals.
final修饰的变量名称需要全部大写
- Only variables that are final should contain capitals (except for underscores in standard prefix/suffix), ‘_tar’ is not final.
只有final修饰的变量名称中才可以有下划线,要么去掉下划线,要么加上final修饰符,Map,List和java对象加上final修饰符后,代表这个对象指向的内存地址不可变,但内容和值都是可以改变的
- Name ‘_targetDataSources’ must match pattern ‘(^[a-z][a-z0-9][a-zA-Z0-9]{0,50}$)’.
变量命名需要符合正则表达式
- The field name indicates a constant but its modifiers do not
变量没有final修饰却使用了final变量的命名规则
- Variables should start with a lowercase character, ‘SUSPEND_MAP’ starts with uppercase character.
普通变量(即没有final修饰)需要驼峰式命名,首字母为小写
- More than 8 parameters (found 9).
构造方法只能有7个参数
- Constructor has 9 parameters, which is greater than 7 authorized.
构造方法只能有7个参数
- Define a constant instead of duplicating this literal “muluList” 6 times.
某个字符串出现了4次或以上,需要定义一个常量来代替
- A method/constructor shouldnt explicitly throw java.lang.Exception
不能直接抛出Exception,需要精确到具体的异常,且最多抛出4个,超过请try catch
- Define and throw a dedicated exception instead of using a generic one.
不能直接抛出Exception,需要精确到具体的异常,且最多抛出4个,超过请try catch
- Remove this useless assignment to local variable “orgnIdL”.
一个没有使用的变量,删掉即可
- Avoid unused private fields such as ‘fastGroup’.
一个没有使用的变量,删掉即可。如果不能删,则将private改为protected或default即可。
- Exceptional return value of java.io.File.mkdirs() ignored in …
mkdirs方法有返回值,如果是false则代表文件夹创建失败,需要处理。判断返回值是否正确,并进行处理,如记日志或抛异常等
- Exceptional return value of java.io.File.delete() ignored in …
delete方法有返回值,如果是false则代表文件删除失败,需要处理。判断返回值是否正确,并进行处理,如记日志或抛异常等
- Use “java.nio.Files#delete” here for better messages on error conditions.
使用Files.delete(file.toPath())来代替file.delete()
- Suspicious comparison of a Integer reference to constant in …
Integer需要使用equals来比较,这是由于超出(-128~127)范围后,==无法比较,但equals性能较低
- Refactor the code in order to not assign to this loop counter from within the loop body.
不要在循环体内操作计数器,重构代码
- Rename “jdbcTemplate” which hides the field declared at line 116.
一个类中变量名称重复,重命名变量名称即可
- Field ssoServer has the same name as a method
一个类中字段名称和方法名称重复,重命名即可
- Merge this if statement with the enclosing one.
多个if可以合并,合并成一个
- Replace the synchronized class “StringBuffer” by an unsynchronized one such as “StringBuilder”.
StringBuffer需要换成StringBuilder
- A “NullPointerException” could be thrown; “dataResults” is nullable here.
在使用对象之前需要对这个对象进行非空判断
- Possible null pointer dereference of track in …
在使用对象之前需要对这个对象进行非空判断
- Update this method so that its implementation is not identical to “getDvStatus” on line 149.
两个方法的内容完全一致,不用写两遍,在其中一个方法中调用另一个方法即可。或者删掉一个,全部使用另一个方法
- Add a nested comment explaining why this method is empty, throw an UnsupportedOperationException or complete the implementation.
空的方法体内部需要写一个注释
- Avoid throwing raw exception types.
自定义一个异常来继承RuntimeException,然后抛出这个自定义的异常,而不是抛出通用的RuntimeException
- Define and throw a dedicated exception instead of using a generic one.
自定义一个异常来继承RuntimeException,然后抛出这个自定义的异常,而不是抛出通用的RuntimeException
- New exception is thrown in catch block, original stack trace may be lost
在catch中抛出异常会使抛出的异常混淆,所以抛出的异常必须带着原异常信息。例如:throw new BusinessException(errorMsg, e)这里第二个参数是必须的
- Avoid empty catch blocks
catch代码块不能为空
- Either remove or fill this block of code.
删掉或填充这个代码块
- Return an empty collection instead of null.
返回空集合Collections.emptyList()而不是null
- Put single-quotes around ‘-‘ to use the faster “indexOf(char)” method.
将双引号改为单引号,理由是用char来找字符比用String来找效率更高
- Method length is 221 lines (max allowed is 200).
一个方法最多200行,试着压缩,实在不行只能拆成多个方法
- Avoid printStackTrace(); use a logger call instead.
catch中使用logger.error来代替e.printStackTrace()。Logger logger = LoggerFactory.getLogger(this.getClass())。记住,logger不可以在数据库对象类中使用
- Remove this expression which always evaluates to “true”
这个判断语句总是为true,删掉即可
- … concatenates strings using + in a loop
在循环中String不要用加号来拼接,而是使用StringBuilder
- Avoid using implementation types like ‘LinkedHashMap’; use the interface instead
在方法的参数中不要使用具体的实现类对象,而是使用它的接口对象。例如:不用LinkedHashMap而用Map
- Iterate over the “entrySet” instead of the “keySet”.
遍历Map不使用keySet而使用entrySet
- … makes inefficient use of keySet iterator instead of entrySet iterator
遍历Map不使用keySet而使用entrySet
- Move constants to a class or enum.
接口中不要定义常量,移到常量类中
- Boxing/unboxing to parse a primitive …
使用parse方法来代替valueOf方法
- Null passed for non-null parameter of …
将一个可能为空的参数传到了一个方法中,但在该方法中,该参数不可为空。修改这个方法,在使用变量前进行非空判断,则这个参数就成为了可为空参数
- Remove this “Integer” constructor
不要使用new Integer来初始化变量的值,使用Integer.valueOf
- new com.model.CatalogInfo() invokes inefficient new Integer(int) constructor; use Integer.valueOf(int) instead
不要使用new Integer来初始化变量的值,使用Integer.valueOf
- HTTP parameter directly written to HTTP header output in …
resp.setHeader(“Content-Disposition”, “attachment;filename = “ + fileName)改为resp.setHeader(“Content-Disposition”, “attachment;filename = “ + new String(fileName.getBytes(“GBK”), “ISO8859-1”))
Relative path traversal in …
new File(filePath + fileName)改为new File(filePath, fileName)。还有使用new FileInputStream(File srcFile)而不是使用new FileInputStream(filePath + fileName)
Boxing/unboxing to parse a primitive …
.valueOf改为.parseXXX,这是由于valueOf返回的是包装类对象,而parseXXX返回的是值
- Use try-with-resources or close this “FileInputStream” in a “finally” clause.
使用try(FileInputStream inFile = new FileInputStream(file)){System.out.println(“…”)}catch{}且不需要finally代码块来关闭,这是jdk1.7的新写法,可以将一些可自动关闭的资源写在try()中,就可以直接实现自动关闭
- Change this “try” to a try-with-resources. (sonar.java.source not set. Assuming 7 or greater.)
使用try(FileInputStream inFile = new FileInputStream(file)){System.out.println(“…”)}catch{}且不需要finally代码块来关闭,这是jdk1.7的新写法,可以将一些可自动关闭的资源写在try()中,就可以直接实现自动关闭
- Replace this use of System.out or System.err by a logger.
System.out换成logger.info。记住,logger不可以在数据库对象类中使用。
- System.out.println is used
System.out换成logger.info。记住,logger不可以在数据库对象类中使用。
- Variable ‘auditTypeName’ must be private and have accessor methods.
只有静态变量才可以用public修饰,所以public改为private或protected或default
- The return value of “valueOf” must be used.
这个语句的返回值必须要被使用,删掉或者使用它
- Return value of String.valueOf(Object) ignored in …
这个语句的返回值必须要被使用,删掉或者使用它
- Synchronize this method to match the synchronization on “setSuspendMap”.
一组get和set方法,如果其中一个方法被synchronized修饰,则另一个也需要使用synchronized 修饰
- An empty statement (semicolon) not part of a loop
双分号导致sonar认为两个分号之间有一个空语句,删掉一个分号即可
- Avoid empty if statements
if代码块不能为空,删掉或填充代码
- A class which only has private constructors should be final
有private构造函数的类需定义为final类
- Class Convert2Track should be declared as final.
该类需定义为final类
- Verify this is the key that was intended; it was already set before.
该key之前已被塞入过一次,一个key塞两次没有意义,去掉一次
- Extract this nested try block into a separate method.
不要在try代码块中再次使用try,去掉内部的,或者把内部的try代码块拉到外面去
- Absolute path traversal in …
直接将文件的绝对路径传到后台,然后生成File对象即会报错。如D:\1.jpg,不可直接传绝对路径,如果知道这个文件会在d盘,可定义常量D:\,然后传值为1.jpg,后台进行拼接后生成File对象即可
- Only one statement per line allowed.
每一行只允许一个语句,可能是多写了分号,去掉即可
- Make this anonymous inner class a lambda (sonar.java.source not set. Assuming 8 or greater.)
jdk1.8之后推荐使用兰布达表达式。请参考:https://blog.csdn.net/qq_33865313/article/details/81203412
- Non-virtual method call in … passes null for non-null parameter of …
将一个可能为空的参数传到了一个方法中,但在该方法中,该参数不可为空。修改这个方法,在使用变量前进行非空判断,则这个参数就成为了可为空参数
- A “NullPointerException” could be thrown; “printStream” is nullable here.
可能会抛出空指针异常,先进行非空判断
- … could be null and is guaranteed to be dereferenced in …
可能会抛出空指针异常,先进行非空判断
- Unused import - …
引入了一个类,但是没有使用,删掉即可
- 2’ is a magic number.
这是一个魔术数字,需要定义一个常量,然后引用常量,而不是直接使用这个数字
- +’ is preceded with whitespace.
代码之前不能有空格,删掉空格即可
- ;’ is not followed by whitespace.
代码之后没有空格,需要添加一个空格
- ?’ is not preceded with whitespace.
代码之前没有空格,需要添加一个空格
- Redundant ‘private’ modifier.
这个修饰符是多余的,删掉该修饰符即可
- Incorrect lazy initialization of static field
对静态变量的延迟初始化有问题。一般可以试着把static修饰符去掉,或者在静态代码块中进行static变量的初始化。
- … Service not allowed Autowired field …
Service中不允许自动注解Manager,一般Service中都是注解其他Service,删掉这个Manager,换成相同功能的Service
- Unread field: … should this field be static?
final修饰的字段需要加上static修饰符
- member def modifier’ has incorrect indentation level 8, expected level should be 4.
缩进不对,可以删掉前面的缩进,用Tab键缩进,或者MyEclipse用Ctrl+Shift+F格式化代码
- Change this code to use a stronger protocol.
修改编码以使用更强壮的协议,照着给的编码改就行
- for child at indentation level 21 not at correct indentation, 20
首行缩进不对,使用Tab键进行缩进
- 0 is a valid index, but is ignored by this check.
0是一个有效的值,但在这里不能用。一般都是要用特殊的值,比如indexOf应该使用>=0或>-1
- Use already-defined constant ‘…’ instead of duplicating its value here.
使用已经定义的常量,而不是在这里复制它的值
- Using the ‘.*’ form of import should be avoided - …
不要使用.*的方式将所有类导入进来,而应该详细的导入每一个用到的类