Such specifications write code, my colleagues call "666"


No. article first appeared in public preserved egg blackboard

Author worked Jingdong, guarantee stability, agile, advanced JAVA, micro-architecture in-depth understanding of service

A, MyBatis do not write for multiple query conditions 1 = 1

After the encounter multiple query, use where 1 = 1 can easily solve our problems, but this is likely to cause great loss of performance, because adding a filter condition "where 1 = 1", the database system you can not use an index such as query optimization strategy, the database system will be forced to scan (ie full table scan) to compare this line meets the filter criteria for each row of data, when the amount of data in the table is large query speed will be very slow ; in addition, there is also the risk of SQL injection.

Counterexample:

<select id="queryBookInfo" parameterType="com.tjt.platform.entity.BookInfo" resultType="java.lang.Integer"> select count(*) from t_rule_BookInfo t where 1=1<if test="title !=null and title !='' "> AND title = #{title} </if> <if test="author !=null and author !='' "> AND author = #{author}</if> </select>复制代码

Positive examples:

<select id="queryBookInfo" parameterType="com.tjt.platform.entity.BookInfo" resultType="java.lang.Integer"> select count(*) from t_rule_BookInfo t<where><if test="title !=null and title !='' "> title = #{title} </if><if test="author !=null and author !='' ">  AND author = #{author}</if></where> </select>复制代码

UPDATE operation, too, may be used instead of a flag = 1.

Second, the iterative entrySet () Retrieves the Map of the key and value

When the loop only needs to acquire Map primary key key, iteration keySet () is correct; however, when you need a primary key key and value value, iteration entrySet () is a more efficient approach, which keySet than the first iteration () by then go get the value of better performance.

Counterexample:

//Map 获取value 反例:HashMap<String, String> map = new HashMap<>();for (String key : map.keySet()){    String value = map.get(key);}复制代码

Positive examples:

//Map 获取key & value 正例:HashMap<String, String> map = new HashMap<>();for (Map.Entry<String,String> entry : map.entrySet()){ String key = entry.getKey(); String value = entry.getValue();}复制代码

Third, the use Collection.isEmpty () detects an empty

Use of a Collection, () is empty is not detected on the logical problems, but using Collection.isEmpty () makes the code more readable, better performance can be obtained; in addition, any Collection.isEmpty () implemented time complexity is O (1), multiple cycles need not traverse, but by a certain time complexity of a Collection, () method implementation may be O (n)

Counterexample:

LinkedList<Object> collection = new LinkedList<>();if (collection.size() == 0){ System.out.println("collection is empty.");}复制代码

Positive examples:

LinkedList<Object> collection = new LinkedList<>();if (collection.isEmpty()){    System.out.println("collection is empty.");}//检测是否为null 可以使用CollectionUtils.isEmpty()if (CollectionUtils.isEmpty(collection)){    System.out.println("collection is null.");}复制代码

Four, designated as far as possible the size of the set of initialization

Try to set the size specified at initialization, can effectively reduce the number of sets of expansion, because each set of expansion when the time complexity is likely to O (n), and time-consuming performance.

Counterexample:

//初始化list,往list 中添加元素反例:int[] arr = new int[]{1,2,3,4};List<Integer> list = new ArrayList<>();for (int i : arr){ list.add(i);}复制代码

Positive examples:

//初始化list,往list 中添加元素正例:int[] arr = new int[]{1,2,3,4};//指定集合list 的容量大小List<Integer> list = new ArrayList<>(arr.length);for (int i : arr){    list.add(i);}复制代码

Fifth, use StringBuilder string concatenation

General string concatenation will be at compile Java optimization, but splice Java compiler optimization of the string can not be executed in a loop, so StringBuilder need to be replaced.

Counterexample:

//在循环中拼接字符串反例String str = "";for (int i = 0; i < 10; i++){    //在循环中字符串拼接Java 不会对其进行优化    str += i;}复制代码

Positive examples:

//在循环中拼接字符串正例String str1 = "Love";String str2 = "Courage";String strConcat = str1 + str2;  //Java 编译器会对该普通模式的字符串拼接进行优化StringBuilder sb = new StringBuilder();for (int i = 0; i < 10; i++){   //在循环中,Java 编译器无法进行优化,所以要手动使用StringBuilder    sb.append(i);}复制代码

VI. To recall Collection.contains method frequently use the Set

In the Java collection class library, List contains the general method of time complexity of O (n), if the code contains method calls frequently find the first set of data is converted into a list HashSet achieved, the O (n) time complexity will be O (1).

Counterexample:

//频繁调用Collection.contains() 反例List<Object> list = new ArrayList<>();for (int i = 0; i <= Integer.MAX_VALUE; i++){    //时间复杂度为O(n)    if (list.contains(i))    System.out.println("list contains "+ i);}复制代码

Positive examples:

//频繁调用Collection.contains() 正例List<Object> list = new ArrayList<>();Set<Object> set = new HashSet<>();for (int i = 0; i <= Integer.MAX_VALUE; i++){    //时间复杂度为O(1)    if (set.contains(i)){        System.out.println("list contains "+ i);    }}复制代码

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>();static {    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<>();static {    list.add("Sagittarius");    list.add("Charming");    list.add("Perfectionist");}复制代码

Eight, delete unused local variables, method parameters, private methods, fields, and extra parentheses.

IX 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();}复制代码

Ten, 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";        }*/    }}复制代码

Eleven, the 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;// "" + valueString strLove = "" + num;复制代码

Positive examples:

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

Twelve, 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);复制代码

XIII, 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();}复制代码

Fourth, priority use constant or call equals method to determine the value

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);}复制代码

Fifth, 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;    }}复制代码

Sixteen, 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"]复制代码


Source: www.liangsonghua.me

Author: Jingdong Senior Engineer - Liang Songhua, in-depth understanding of the stability of security, agile development, JAVA advanced, micro-service architecture


Guess you like

Origin juejin.im/post/5daf08cd6fb9a04e19506704