Are you crazy, you "poisoned" the code?

Are you crazy, you "poisoned" the code?

 

I. Introduction

Can't remember the learned code? You can't remember the wrong way, you remember!

  • Git : Going to the toilet is not called going to the toilet, it is called pulling a branch!
  • Socket : The toilet is the server, and the pit is the port!
  • Queue : Call in the queue when going to the toilet, first in, first out!
  • Zhan : Go to the kitchen and call Jin Zhan, last in first out!
  • Architecture : The three-bedroom layout is called MVC, and the four-bedroom layout is called DDD!
  • Theory : The system structure is well designed, and there is no problem with some bugs. It can be changed. This is the difference between Mao Keng and toilet.

Except for a little taste, I don’t remember this time . The process of programming and writing code and the examples of our daily life are often like this. With real objects that can be touched, it will be easier to understand programming. , It’s hard to forget. But he might just laugh while writing code!

In addition to these positive energy learning examples, let's take a look at the toxic code next!

2. The code is poisonous!

The following code is good for promotion and salary increase, but it is not good for expulsion!

1. Method naming

public List<UserInfo> queryBitchUserInfo(String req) {
    return null;
}

  • Index: ★★★
  • Detoxification: little brother should be to write a batch query method name of the user, the results of the batch ( batch ), written bitch ( bitch )
  • Comment: The interface is written in the morning, and people leave in the afternoon!

2. Best Sorting

public static void main(String[] args) {
    int[] numbers = new int[]{2, 30000000, 1, 6, 40000000, 5};
    for (final int number : numbers) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(number);                    System.out.println(number);                } catch (InterruptedException ignore) {
                }            }        }).start();    }}

  • Index: ★★★
  • Detoxification: Always sort by digital sleep, whoever wakes up early will output first.
  • Comment: The idea is very strange, if it weren't for this sort of waiting for a day, the boss could not kick him!

3. Little brains

@Test
public void test_idx_hashMap() {
    Map<String, String> map = new HashMap<>(64);
    map.put("alderney", "未实现服务");
    map.put("luminance", "未实现服务");
    map.put("chorology", "未实现服务");
    map.put("carline", "未实现服务");
    map.put("fluorosis", "未实现服务");
    map.put("angora", "未实现服务");
    map.put("insititious", "未实现服务");
    map.put("insincere", "已实现服务");
        long startTime = System.currentTimeMillis();
    for (int i = 0; i < 100000000; i++) {
        map.get("insincere");
    }    System.out.println("耗时(initialCapacity):" + (System.currentTimeMillis() - startTime));
}

  • Index: ★★★★★
  • Detoxification: This is a function that defines the HashMap storage business to realize the key, and calls the service through the key. But the key here is only useful for insincere, and the others are unimplemented services. Do you see any problems? At first glance, there is nothing wrong with this code, but if you understand it, there is arsenic in the code! Its purpose is one, to put all the keys into a linked list and put them in the HashMap, and put useful keys at the end of the linked list, increasing the time-consuming get!  First of all, new HashMap<>(64); Why initialize 64 lengths by default? Because the default length is 8, when inserting elements, when the length of the linked list is 8, the expansion and the tree of the linked list will be judged. At this time, the original key will be hashed, and all keys cannot be made into a high time complexity Linked list. Secondly, all keys are deliberately selected, because when they calculate the index in HashMap, the index value is 0, idx = (size-1) & (key.hashCode() ^ (key.hashCode()> >> 16)), so that all keys can be hashed to the same location for collision. And the word insincere means; insincere, insincere!  Finally, the first 7 keys are actually useless keys and have no effect. Only the last key has service. In this way, a lot of such time-consuming collision lists can be built in HashMap, of course, the load factor of 0.75 must be met, and the HashMap should not be expanded. The overall effect is as shown below, the key is not evenly hashed;
  • Comment: If you can write this kind of code, the salary is not enough, waiting for the code optimization to raise the salary!

4. Summation of the Mystery

@Test
public void test_add(){
    int num = 0;
    for (int i = 0; i < 100; i++) {
        num = num++;    }    System.out.println(num);
}

  • Index: ★★
  • Detoxification: The final result of num is 0, and num++ has no effect at all. Because after ++, the result is used first, and the ++ operation will not assign a value. The correct writing is: num = ++ num;
  • Comments: This kind of mistake is like driving through a red light, ranging from deduction and fines to ruin.

5. Fancy

private boolean checkAge(int age ) {
    boolean result;
    if (age >18) 
    {        result=true;
    } else {
        result=false;
    }            return result;
}

  • Index: ★
  • Detoxification: The code can run, but it can be optimized to return age> 18.
  • Comment: Does your company hit performance based on the number of lines of code? No formatting, untidy, or IDEA tooltips, the code is written for people to see! What is it!

6. Number Judgment

public boolean isNumber(String str) {
    try {
        Integer.parseInt(str);        return true;
    } catch (Exception e) {
        return false;
    }}

  • Index: ★★
  • Detoxification: Judge whether it is a number, don't throw an exception, or throw an exception. This can be judged using StringUtils toolkit, or you can write regular judgments yourself.
  • Comment: This code is really burned, use exceptions for business. Isn't this giving mushrooms to dogs? If the dog is not dead, you eat mushrooms, you eat goubaba.

7. Robust code

public void neverStop(){
    //一直循环
    while (true) {
        try {
            //业务处理流程
        } catch (Exception e) {
            //抓到异常,不处理、不打日志、就是不要停,继续跑
            continue ;
        }    }}

  • Index: ★★★
  • Detoxification: Wrap the code that may throw exceptions with tryCatch, keep running, and run when encountering exceptions. If you encounter an exception at this time, you need to do some process processing, at least log and alarm.
  • Comment: Business development is often used to solve abnormal processes, just like 80% of the area of ​​rubbing paper is to protect hands. How to drop it, I see your code, it must be broken!

8. Performance optimization

// APP首页查询,优化前
public void queryInitInfo(){
    Thread.sleep(3000);
}
// APP首页查询,优化后
public void queryInitInfo(){
    Thread.sleep(500);
}

  • Index: ★★★
  • Detoxification: There is nothing to detoxify, one kilogram of Crane Dinghong added a sip of water!
  • Comment: I can't comment, let's open it when you catch it!

9. Useless logs

// 规则引擎校验
public boolean ruleEngine(MatterReq req) {    try {
        // 业务流程
    } catch (Exception e) {
        logger.error(e);  // 只打异常,不打入参信息
    }}

  • Index: ★
  • Detoxification: Only exceptions are entered in the log, and no parameter information is entered. When your method has a large number of calls, it is difficult to quickly locate the problem.
  • Comment: Next time, remember to log the product manager as well, and die together!

10. Time-consuming traversal

@Test
public void test_LinkedList() {
    // 初始化100万数据
    List<Integer> list = new LinkedList<Integer>(1000000);
    
    // 遍历求和
    int sum = 0;
    for (int i = 0; i < list.size(); i++) {
        sum += list.get(i);
    }
    
}

  • Index: ★★★★
  • Detoxification: At first glance, it may seem that there is no problem, but this traversal and summation will be very slow. Mainly because of the data structure of the linked list, every list.get(i) is searched from the head of the linked list. Unlike ArrayList, LinkedList has a time complexity of O(n). So if you don’t know if the other party passed LinkedList or ArrayList, you can actually judge it by list instanceof RandomAccess. ArrayList is implemented in random access, but LinkedList is not. You can also use the enhanced for loop or Iterator to traverse.
  • Comment: The foundation is not strong, the ground shakes! With a little knowledge, I pit the old iron!

Three, summary

Good code is the same, bad program appreciates and raises salary! , These toxic codes vividly demonstrated the outstanding talents of programmers, and also seriously suspected that the money was given less!

Guess you like

Origin blog.csdn.net/python8989/article/details/108468390