快捷搜索: 王者荣耀 脱发

sonar常见问题及修改建议

如今,大家都用sonar工具扫描自己的项目代码,以提高自己的代码质量。关于sonar工具的使用以及本地sonar环境搭建已经有同事在内网上分享了,本文不再介绍。本文主要介绍自己在工作中用soanr工具检查JAVA代码时常见的问题及对应修改建议,对有些问题还做了修改分析。文中如有不妥的地方或者有更好的建议,欢迎给我发邮件讨论。

常见问题1:

使用字符索引 : String.indexOf(char) is faster than String.indexOf(String).

代码举例: if(splitArray[i].indexOf("}")!=-1)

修改建议: if(splitArray[i].indexOf(})!=-1)

常见问题2:

在进行比较时,字符串文本应该放在左边 : Move the "0" string literal on the left side of this string comparison.

代码举例: if(enNameArray[1].equals("0")){

enName = enNameArray[2];

}

修改建议: if("0".equals(enNameArray[1])){ .......

常见问题3:

应该使用Collection.isEmpty()判断空集合 : Use isEmpty() to check whether the collection is empty or not.

代码举例: if(names.size() == 0){

.........

}

修改建议: if(names.isEmpty()){ .......

常见问题4:

返回之前不用的本地变量 : Consider simply returning the value vs storing it in local variable flightLineQueryForm.

代码举例:

修改建议:

常见问题5:

整型实例 : Avoid instantiating Integer objects. Call Integer.valueOf() instead.代码举例: properties.put("CCSID", new Integer(req.getQueueCCSID()));

修改建议: properties.put("CCSID", Integer.valueOf(req.getQueueCCSID()));

修改分析:JDK1.5后增加了Integer.valueOf. 因此1.5前不能用.从源代码可以知道,ValueOf对-128~127这256个值做了缓存(IntegerCache),如果int值的范围是:-128~127,在ValueOf(int)时,会直接返回IntegerCache的缓存。

常见问题6:

低效的StringBuffer : Avoid concatenating nonliterals in a StringBuffer constructor or append().

代码举例: retStr.append("PNR:"+locatorID);

修改建议: retStr.append("PNR");

retStr.append(locatorID);

常见问题7:

精确初始化 : Variable bEnvInited explicitly initialized to false (default value for its type).

代码举例: private static boolean bEnvInited = false;

修改建议: private static boolean bEnvInited;

常见问题8:

精确初始化 : 应该合并可折叠的"if"语句 : Merge this if statement with the enclosing one.

代码举例:

修改建议:

常见问题9:

方法名需要遵守命名规则 : Rename this method name to match the regular expression ^[a-z][a-zA-Z0-9]*$.

代码举例: private boolean ISpasstype(String type) {......

修改建议: private boolean iSpasstype(String type) {......

常见问题10:

避免在循环体中声明创建对象.

代码举例:

修改建议:

常见问题11:

常量名应该遵守命名规则 : Rename this constant name to match the regular expression ^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$.

代码举例: protected static final String HomophoneRule="Homophone";

修改建议: protected static final String HOMOPHONE_RULE="Homophone";

常见问题12:

安全 - 直接保存数组 : The user-supplied array destCityArray is stored directly.代码举例:

修改建议:

常见问题13:

类变量不应该有公开访问权限 : Make this class field a static final constant or non-public and provide accessors if needed.

代码举例:

public static Timestamp foreverLong = SimpleDate.MaxDate().getTimestamp();

修改建议:

private static Timestamp foreverLong = SimpleDate.MaxDate().getTimestamp();

总结

经验分享 程序员 微信小程序 职场和发展