1. 程式人生 > >【程式碼審查】C#部分規則詳細說明一

【程式碼審查】C#部分規則詳細說明一

1.The members of an interface declarationor class should appear in a pre-defined order 

正確的順序如下所示:靜態成員變數→成員變數→構造器→方法 

public class Foo{ 

public static final int OPEN = 4;  //Class and instance variables 

private int field = 0; 

public Foo() {...}    //Constructors 

public boolean isTrue() {...}    //Methods 

} 

2.The diamond operator("<>") should be used 

Noncompliant Code Example:不規範的示例 

List<String>  strings = new ArrayList<String>();  // Noncompliant 

Map<String, List<Integer>> map= new HashMap<String, List<Integer>>();  // Noncompliant 

Compliant Solution :規範的示例 

List<String> strings = newArrayList<>();

Map<String, List<Integer>> map= new HashMap<>(); 

3.Sections of code should not be"commented out" 

程式碼片段不應該出現在註釋中,這樣會bloat程式,可讀性變差 

Programmers should not comment out code asit bloats programs and reduces readability. 

Unused code should be deleted and can beretrieved from source control history if required.

4.Utility classes should not have publicconstructors 

工具類不應該有public的構造器,也就是工具類至少要定義一個non-public的構造器 

Utility classes, which are a collection ofstatic members, are not meant to be instantiated. Even abstract utilityclasses, which can be extended, should not have public constructors. 

Java adds an implicit public constructor toevery class which does not define at least one explicitly. Hence, at least onenon-public constructor should be defined. 

class StringUtils { // Noncompliant CodeExample 

   public static String concatenate(String s1, String s2) { 

         return s1 + s2; 
    } 
} 
class StringUtils { //Compliant Solution 

    privateStringUtils() { 

    } 
   public static String concatenate(String s1, String s2) { 

   return s1 + s2; 
    }
}