Some code specification (b) often encountered

Seven, the use of static code block implements static member variable assignment

 For static member variables collection types, you should use static code block assignment, instead of using a set of implementation to evaluation.

Counterexample:

private static Map<String, Integer> map = new HashMap<String, Integer>(){
    {
        map.put("Leo",1);
        map.put("Family-loving",2);
        map.put("Cold on the out side passionate on the inside",3);
    }
};
private static List<String> list = new ArrayList<>(){
    {
        list.add("Sagittarius");
        list.add("Charming");
        list.add("Perfectionist");
    }
};

Positive examples: 

private static Map<String, Integer> map = new HashMap<String, Integer>(){
    {
        map.put("Leo",1);
        map.put("Family-loving",2);
        map.put("Cold on the out side passionate on the inside",3);
    }
};
private static List<String> list = new ArrayList<>(){
    {
        list.add("Sagittarius");
        list.add("Charming");
        list.add("Perfectionist");
    }
};

 Eight, tools shield constructor

 Tools is a collection of a bunch of static fields and functions, which should not be instantiated; however, Java adds an implicit public constructor for each class is not explicitly defined constructor, in order to avoid unnecessary instantiation, should explicit definition of private constructors to shield the implicit public constructor.

Counterexample:

public class PasswordUtils {
//工具类构造函数反例
private static final Logger LOG = LoggerFactory.getLogger(PasswordUtils.class);

public static final String DEFAULT_CRYPT_ALGO = "PBEWithMD5AndDES";

public static String encryptPassword(String aPassword) throws IOException {
    return new PasswordUtils(aPassword).encrypt();
}

Positive examples:

public class PasswordUtils {
//工具类构造函数正例
private static final Logger LOG = LoggerFactory.getLogger(PasswordUtils.class);

//定义私有构造函数来屏蔽这个隐式公有构造函数
private PasswordUtils(){}

public static final String DEFAULT_CRYPT_ALGO = "PBEWithMD5AndDES";

public static String encryptPassword(String aPassword) throws IOException {
    return new PasswordUtils(aPassword).encrypt();
}

Nine, remove the extra exception caught and ran

After capturing an exception with catch phrase, if nothing is processed, it just makes an exception is thrown again, this result is not like catching exceptions, you can delete or add another piece of code that process.

Counterexample: 

//多余异常反例
private static String fileReader(String fileName)throws IOException{

    try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
        String line;
        StringBuilder builder = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }
        return builder.toString();
    } catch (Exception e) {
        //仅仅是重复抛异常 未作任何处理
        throw e;
    }
}

 Positive examples:

//多余异常正例
private static String fileReader(String fileName)throws IOException{

    try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
        String line;
        StringBuilder builder = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }
        return builder.toString();
        //删除多余的抛异常,或增加其他处理:
        /*catch (Exception e) {
            return "fileReader exception";
        }*/
    }
}

X. string conversion using String.valueOf (value) instead of "" + value

When the type or other objects into a string, using String.valueOf (value) "" + is higher than the efficiency value.

Counterexample:

//把其它对象或类型转化为字符串
int num = 520;
// "" + value
String strLove = "" + num;

Positive examples:

//把其它对象或类型转化为字符串
int num = 520;
// String.valueOf() 效率更高
String strLove = String.valueOf(num);

XI avoid using BigDecimal (double)

BigDecimal (double) the presence of risk of loss of precision, the exact calculation of the comparison values ​​or the scene may cause the business logic exception.

Counterexample:

// BigDecimal 
BigDecimal bigDecimal = new BigDecimal(0.11D);

Positive examples:

// BigDecimal 
BigDecimal bigDecimal1 = bigDecimal.valueOf(0.11D);

Twelve, returns an empty array rather than null and collections

If the program run returns null, null square mandatory testing needs to be called, otherwise it will throw null pointer exception; returns an empty array or an empty set, effectively avoid the situation because the caller does not detect null null pointer exception is thrown, you can also delete the caller detect null statement makes the code more concise.

Counterexample:

//返回null 
public static Result[] getResults() {
    return null;
}

public static List<Result> getResultList() {
    return null;
}

public static Map<String, Result> getResultMap() {
    return null;
}

Positive examples:

//返回空数组和空集
public static Result[] getResults() {
    return new Result[0];
}

public static List<Result> getResultList() {
    return Collections.emptyList();
}

public static Map<String, Result> getResultMap() {
    return Collections.emptyMap();
}

Thirteen, or determine the value of using a constant priority call the equals method

equals method of Object readily shorting pointer exception, should be used with a constant value or determined object to call the equals method.

Counterexample:

//调用 equals 方法
private static boolean fileReader(String fileName)throws IOException{

 // 可能抛空指针异常
 return fileName.equals("Charming");
}

Positive examples:

//调用 equals 方法
private static boolean fileReader(String fileName)throws IOException{

    // 使用常量或确定有值的对象来调用 equals 方法
    return "Charming".equals(fileName);

    //或使用:java.util.Objects.equals() 方法
   return Objects.equals("Charming",fileName);
}

Fourth, the enumeration of attribute fields must be private and immutable

Enumeration is generally used as a constant, or if the common attribute field setting field enumeration methods exist, then the enumeration constant properties can easily be modified; ideally, enumeration property fields are private, proprietary and constructor, assignment, there is no corresponding method Setter, preferably together with the final modifier.

Counterexample:

public enum SwitchStatus {
    // 枚举的属性字段
    DISABLED(0, "禁用"),
    ENABLED(1, "启用");

    public int value;
    private String description;

    private SwitchStatus(int value, String description) {
        this.value = value;
        this.description = description;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}

Positive examples:

public enum SwitchStatus {
    // 枚举的属性字段
    DISABLED(0, "禁用"),
    ENABLED(1, "启用");

    // final 修饰
    private final int value;
    private final String description;

    private SwitchStatus(int value, String description) {
        this.value = value;
        this.description = description;
    }

    // 没有Setter 方法
    public int getValue() {
        return value;
    }

    public String getDescription() {
        return description;
    }
}

Fifteen, tring.split (String regex) part of a keyword needs translation

When using plit string String method, passing in the delimited string is a regular expression, then part of the keyword (such as [] () |., Etc.) need to be escaped.

Counterexample:

// String.split(String regex) 
String[] split = "a.ab.abc".split(".");
System.out.println(Arrays.toString(split));   // 结果为[]

String[] split1 = "a|ab|abc".split("|");
System.out.println(Arrays.toString(split1));  // 结果为["a", "|", "a", "b", "|", "a", "b", "c"]

Positive examples:

// String.split(String regex) 
// . 需要转译
String[] split2 = "a.ab.abc".split("\\.");
System.out.println(Arrays.toString(split2));  // 结果为["a", "ab", "abc"]

// | 需要转译
String[] split3 = "a|ab|abc".split("\\|");
System.out.println(Arrays.toString(split3));  // 结果为["a", "ab", "abc"]
Published 31 original articles · won praise 14 · views 9534

Guess you like

Origin blog.csdn.net/weixin_42555514/article/details/103120033