How to write code so that the interviewer can see it? The boss teaches you how to eat.

table of Contents

1. MyBatis do not write 1 = 1 for multiple query conditions

2. Iterate the entrySet() to get the key and value of the Map

Three, use Collection.isEmpty() to detect empty

Fourth, try to specify its size when initializing the collection

Five, use StringBuilder to splice strings

6. If you need to call the Collection.contains method frequently, use Set

Seven, use static code blocks to realize the assignment of static member variables

8. Delete unused local variables, method parameters, private methods, fields, and extra parentheses.

Nine, shield constructor in tool class

Ten, delete redundant exception capture and run out


After working for a few months, I feel that my code is very irregular, with a lot of redundancy and messy. How can I improve the code specification in a targeted manner?

Let's share an actual operation of the standard code.

The code can be written as 666, can the boss accept disciples?

1. MyBatis do not write 1 = 1 for multiple query conditions

When encountering multiple query conditions, using where 1=1 can easily solve our problem, but this is likely to cause a very large performance loss, because after adding the filter condition of "where 1=1", the database system It is impossible to use query optimization strategies such as indexes. The database system will be forced to scan each row of data (ie full table scan) to compare whether the row meets the filter conditions. When the amount of data in the table is large, the query speed will be very slow ; In addition, there will be 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>

Normal example:

<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>

The same is true for the UPDATE operation, you can use a flag instead of 1=1.

2. Iterate the entrySet() to get the key and value of the Map

When only the primary key key of the Map needs to be obtained in the loop, iterating keySet() is correct; however, when the primary key key and the value value are needed, iterating entrySet() is more efficient than iterating keySet() first. It is better to get the value through get later.

Counterexample:

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

Normal example:

//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();
}

Three, use Collection.isEmpty() to detect empty

Using Collection.size() to detect whether it is empty is logically no problem, but using Collection.isEmpty() makes the code more readable and can achieve better performance; in addition, any Collection.isEmpty() implementation The time complexity is O(1), and there is no need to loop through it multiple times, but some of the time complexity achieved by the Collection.size() method may be O(n)

Counterexample:

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

Normal example:

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.");

}

Fourth, try to specify its size when initializing the collection

Try to specify the size of the collection during initialization, which can effectively reduce the number of expansions of the collection, because the time complexity of each expansion of the collection is likely to be O(n), which consumes time and performance.

Counterexample:

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

Normal example:

//初始化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);
}

Five, use StringBuilder to splice strings

General string splicing is optimized by Java during compile time, but string splicing in a loop cannot be optimized during Java compile time, so StringBuilder needs to be used for replacement.

Counterexample:

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

Normal example:

//在循环中拼接字符串正例
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);
}

6. If you need to call the Collection.contains method frequently, use Set

In the Java collection class library, the general time complexity of the contains method of List is O(n). If the contains method needs to be frequently called in the code to find data, first convert the collection list into a HashSet implementation, and the time complexity of O(n) 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);
}

Normal example:

//频繁调用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, use static code blocks to realize the assignment of static member variables

For static member variables of the collection type, static code block assignment should be used instead of using the collection implementation to assign values.

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");
    }
};

Normal example:

//赋值静态成员变量正例
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");
}

8. Delete unused local variables, method parameters, private methods, fields, and extra parentheses.

Nine, shield constructor in tool class

The utility class is a collection of static fields and functions, which should not be instantiated; however, Java adds an implicit public constructor for each class without a clearly defined constructor. In order to avoid unnecessary instantiation, you should Explicitly define a private constructor to shield this 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();
}

Normal example:

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, delete redundant exception capture and run out

After catching the exception with the catch statement, if nothing is processed, just let the exception be re-thrown, which is the same as not catching the exception. You can delete this piece of code or add other processing.

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;
    }
}

Normal example:

//多余异常正例
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";
        }*/
    }
}

The article ends here

In order for us to write code more standardized, Xiao Bian here to prepare a handbook for everyone Alibaba development, we need little friends can point me to the point I free pick oh 

If you like the editor’s sharing, you can like and follow it. The editor will continue to share the latest articles and receive benefits for you.

Guess you like

Origin blog.csdn.net/SQY0809/article/details/109361559