您的位置:首页 > 编程语言

代码与流程规范

2019-05-22 17:36 295 查看

本文整理在开发过程中遇到的一些代码规范问题,主要依据是SonarLint的代码质量检测。

1、工具类不应该存在公有构造方法

Utility classes, which are collections of static members, are not meant to be instantiated. Even abstract utility classes, which can be extended, should not have public constructors.
Java adds an implicit public constructor to every class which does not define at least one explicitly. Hence, at least one non-public constructor should be defined.

不好的例子

class StringUtils {

public static String concatenate(String s1, String s2) {      
return s1 + s2;    
}  

}

好的例子

class StringUtils {

private StringUtils() {      
throw new IllegalStateException("Utility class");    
}      

public static String concatenate(String s1, String s2) {     
return s1 + s2;    
}    

}  
Assignments should not be made from within sub-expressions
Assignments within sub-expressions are hard to spot and therefore make the code less readable. Ideally, sub-expressions should not have side-effects.
Noncompliant Code Example
 if ((str = cont.substring(pos1, pos2)).isEmpty()) { // Noncompliant    //...  
Compliant Solution
 str = cont.substring(pos1, pos2);  if (str.isEmpty()) {    //...  
Exceptions
Assignments in while statement conditions, and assignments enclosed in relational expressions are ignored.
 BufferedReader br = new BufferedReader(/* ... */);  String line;  while ((line = br.readLine()) != null) {...}  
Chained assignments, including compound assignments, are ignored.
 int i = j = 0;  int k = (j += 1);  result = (bresult = new byte[len]);  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: