Learn code optimization from Sonar-code smell case

Sonar believes that everyone is familiar with it. Many companies use Sonar as a tool for code quality testing, and use Sonar to examine the quality of software and the level of programmers. When we modified the code smell, we also gradually improved our coding level.

image

Let's take a look at some common code problems in Sonar.

Comparison of packaging objects

Case code

//两边都为Integer类型
if(xxx.getLevel() == xxx.getCurrentLevel()) {
    ...
}

Sonar detection problem

The value comparison between all packaging objects, all use the equals method to compare

For Integer var=?assignments between -128 and 127, the Integerobject is being IntegerCache.cachegenerated, and the existing object will be reused. The Integervalue in this interval can be directly judged with ==, but all data outside this interval will be generated on the heap , And will not reuse existing objects. This is a big pit. It is recommended to use the equals method for judgment.

That is to say, if you are using the packaging type Integer, although it can be judged with == between -128 and 127, if the value exceeds this value, it is a comparison between two objects. The equal sign is invalid. And we are comparing content, so we use equals.

@Test
public void testInteger() {

    Integer a1 = 120;
    Integer a2 = 120;
    System.out.println("a1 == a2: " + (a1 == a2));

    Integer a3 = 200;
    Integer a4 = 200;
    System.out.println("a3 == a4: " + (a3 == a4));

    System.out.println("a3.equals(a4): " + (a3.equals(a4)));
}

operation result:

a1 == a2: true
a3 == a4: false
a3.equals(a4): true

Manually create a thread pool, the effect will be better

Case code

private static ExecutorService executor = Executors.newSingleThreadExecutor();

Disadvantages of each method of Executors:

  • newFixedThreadPoolAnd newSingleThreadExecutor: The main problem is that the piled up request processing queue may consume very large memory, or even OOM.

  • newCachedThreadPoolAnd newScheduledThreadPool: The main problem is that the maximum number of threads is Integer.MAX_VALUEthat a very large number of threads may be created, or even OOM.

Here is the recommended ThreadPoolExecutorway to create.

Example of use:

ExecutorService pool = new ThreadPoolExecutor(5, 200,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue <Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());

        pool.execute(()-> System.out.println(Thread.currentThread().getName()));
        pool.shutdown();

When using regular expressions, make good use of its pre-compilation function, which can effectively speed up regular matching

Case code

 Pattern pattern = Pattern.compile("^[1]\\d{10}$");

Do not define in the method body:Pattern pattern = Pattern.compile(规则);

The correct way to use:

public class XxxClass {  
        private static Pattern NUMBER_PATTERN = Pattern.compile("^[1]\\d{10}$");
        public static Pattern getNumberPattern() {  
           return NUMBER_PATTERN;
        }
    }

When the collection is initialized, specify the initial value of the collection

Case code

Map<String, Object> cache = new HashMap<>();

HashMap uses the following construction method to initialize. If the collection size cannot be determined temporarily, then specify the default value (16).

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

Arrays.asList()与Collections.singletonList()

Arrays.asList(strArray)The return value is still a variable set, but the return value is its internal class, does not have an add method, you can increase the value through the set method, the default length is 10, and the Collections.singletonList()return is also an immutable set, but a set of this length Only 1, can reduce the memory space. But the returned value is still the internal implementation class of Collections, and there is also no add method. Calling the add and set methods will report an error.

Guardian statement reduces if-else nesting

The logic judgment code of if-else with more than 3 layers can be realized by using guard sentence, strategy mode, state mode, etc.

Example:

    public void today() {
      if (isBusy()) {
       System.out.println(“change time.”);
       return; 
      }
      if (isFree()) {
       System.out.println(“go to travel.”);
       return;
      }
      return;
    }

SimpleDateFormat is not thread safe and should not be defined as a static variable

We can use local thread processing:

private static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>() {
     @ Override
     protected DateFormat initialValue() {
      return new SimpleDateFormat("yyyy-MM-dd");
     }
};

Recommended in the past

Scan the QR code to get more exciting. Or search Lvshen_9 on WeChat , you can reply to get information in the background

回复"java" 获取java电子书;

回复"python"获取python电子书;

回复"算法"获取算法电子书;

回复"大数据"获取大数据电子书;

回复"spring"获取SpringBoot的学习视频。

回复"面试"获取一线大厂面试资料

回复"进阶之路"获取Java进阶之路的思维导图

回复"手册"获取阿里巴巴Java开发手册(嵩山终极版)

回复"总结"获取Java后端面试经验总结PDF版

回复"Redis"获取Redis命令手册,和Redis专项面试习题(PDF)

回复"并发导图"获取Java并发编程思维导图(xmind终极版)

Another: Click [ My Benefits ] to have more surprises.

Guess you like

Origin blog.csdn.net/wujialv/article/details/115324949