sonar代码检查

来源:互联网 发布:仓位在线软件 编辑:程序博客网 时间:2024/06/08 11:12

常见问题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-128127256个值做了缓存(IntegerCache),如果int值的范围是:-128127,在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(); 

总结

本文介绍的主要是自己在用SONAAR修改JAVA代码中经常遇到的代码质量问题,自己总结了了一些修改方法,在此给大家分享一下。由于写作水平和能力有限,文中如有不妥的地方或者有更好的建议,欢迎联系我。

0 0
原创粉丝点击