代码与流程规范

本文整理在开发过程中遇到的一些代码规范问题,主要依据是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;    
    }    

}  

2、逻辑判断代码中不应该存在子表达式

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.

会导致可读性差

不好的例子

if ((str = cont.substring(pos1, pos2)).isEmpty()) {
 
            // Noncompliant    //...  

好的例子

str = cont.substring(pos1, pos2);  
if (str.isEmpty()) {    
    //...  

3、应使用Collection.isEmpty用来判断集合是否为空

Using Collection.size() to test for emptiness works, but using Collection.isEmpty() makes the code more readable and can be more performant. The time complexity of any isEmpty() method implementation should be O(1) whereas some implementations of size() can be O(n).

不好的例子

if (myCollection.size() == 0) { 
    // Noncompliant    /* ... */  
}

好的例子

if (myCollection.isEmpty()) {   
     /* ... */ 
 }

4、声明和定义的正确顺序

Modifiers should be declared in the correct order

The Java Language Specification recommends listing modifiers in the following order:

  1. Annotations
  2. public
  3. protected
  4. private
  5. abstract
  6. static
  7. final
  8. transient
  9. volatile
  10. synchronized
  11. native
  12. strictfp

不好的例子

static public void main(String[] args) { // Noncompliant  }

好的例子

public static void main(String[] args) { // Compliant  }  

5、本地变量应该快速返回

Declaring a variable only to immediately return or throw it is a bad practice.
Some developers argue that the practice improves code readability, because it enables them to explicitly name what is being returned. However, this variable is an internal implementation detail that is not exposed to the callers of the method. The method name should be sufficient for callers to know exactly what will be returned.

不好的例子


public long computeDurationInMilliseconds() {   

     long duration = (((hours * 60) + minutes) * 60 + seconds ) * 1000 ;    

    return duration;  

}    

public void doSomething() {    

    RuntimeException myException = new RuntimeException();    

    throw myException;  

}

好的例子


 public long computeDurationInMilliseconds() {    

    return (((hours * 60) + minutes) * 60 + seconds ) * 1000 ;  

}    

public void doSomething() {       

    throw new RuntimeException();  

}

6、"public static"修饰的变量应该被常量化

There is no good reason to declare a field "public" and "static" without also declaring it "final". Most of the time this is a kludge to share a state among several objects. But with this approach, any object can do whatever it wants with the shared state, such as setting it to null.

不好的例子


public class Greeter {    

    public static Foo foo = new Foo();    ...  

}

好的例子


public class Greeter {    

    public static final Foo FOO = new Foo();    ...  

}  

7、尽量减少变量的重复计算

for (int i = 0; i < list.size(); i++)
{...}

改为

for (int i = 0, length = list.size(); i < length; i++)
{...}

8、尽量采用懒加载的策略


String str = "aaa";
if (i == 1){
  list.add(str);
}

改为


if (i == 1){
  String str = "aaa";
  list.add(str);
}

9、使用equals时,字符串放在变量前面

可以避免空指针


String str = "123";
if ("123".equals(str))
{
    ...
}

10、应该返回空的数组或集合,而不是null

不好的例子


 public static List<Result> getResults() {    
return null; // Noncompliant  }    

public static Result[] getResults() {    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) {        

/* ... */     

 }    

}  

}

好的例子


public static List<Result> getResults() {    
return Collections.emptyList(); // Compliant  
}    

public static Result[] getResults() {    
return new Result[0];  
}    

public static void main(String[] args) {    
for (Result result: getResults()) {      /* ... */    }  
}

参考文档

[1]: 44个Java性能优化手段,效率杠杠的!
[2]: 在Java中如何优雅地判空
[3]: SEI CERT Oracle Coding

转载于:https://www.cnblogs.com/fonxian/p/10907409.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值