当前位置:网站首页>Code quality management

Code quality management

2022-07-07 03:25:00 qq_ thirty-seven million seven hundred and five thousand five h

Code quality management

1 Make pushDataList a static final constant or non-public and provide accessors if needed.

 Insert picture description here
Class variable fields should not have public accessibility . So the public Access modifier , Change to other modifiers , It is best to private.

Public class variable fields don't respect encapsulation principles , There are three main drawbacks :
Can't add other behavior , Such as verification .
The internal representation is public , You can't change it later .
Member values can change anywhere in the code , And it may not fit the programmer's assumptions .
By using private properties and accessor methods (set and get), Can prevent unauthorized modification .

There's no good reason not to declare fields “final” In this case, declare the field “public” and “static”. Most of the time , This is an error sharing state between multiple objects . But in this way , Any object can do whatever it wants with the shared state , For example, set it to null .

2 Use Galois/Counter Mode (GCM/NoPadding) instead

3 Remove this call to “equals”; comparisons between unrelated types always return false.

Delete the "equals" Call to ; Comparisons between unrelated types always return false.

   if (transportTask.getTaskType().equals("1") || transportTask.getTaskType().equals("4")) {}
   
transportTask.getTaskType() by Short type , therefore if Forever false
short  The data type is  16  position 、 A signed integer represented by a binary complement 
 The minimum is  -32768(-2^15);
 The maximum is  32767(2^15 - 1);
Short  Data types can also be like  byte  That saves space . One short A variable is int One-half of the space occupied by the type variable ;
 The default value is  0;

 Example :short s = 1000,short r = -20000.
short It will be promoted to int Type or higher . This is because Java Will automatically short Data is treated as a int The literal value of the type (literal) To deal with .byte The same is true when types do operations , Will be java Automatically upgrade the level .

short  yes  Java  The original type .short  Variables can be stored 16 A signed integer .
Short  Class is  short  Wrapper object class of original type . It defines the range of values that represent this type  MIN_VALUE  and  MAX_VALUE  Constant .
Java  All integer values in are  32  Bit  int  value , Except after the value  l  or  L( Such as  235L), This means that the value should be interpreted as  long.

4 Cast one of the operands of this integer division to a “double”

        Cast one of the operands of this division operation to a "double"

Convert one operand of this division operation to "double"

Very basic , In the coding process , Mistakes that are easy to be ignored , Divide two integers , The result must be an integer ,
If you use float、double Wait for data type reception , Grammar does not constitute a mistake , But it will lose precision .

/**

  • @author css

  • @date 2019/9/30 9:39
    */
    public class Test {
    public static void test(double d){
    System.out.println(d);
    }

    public static void main(String[] args) {
    int a = 1;
    int b = 2;
    test(a/2);
    float c = a/b;
    System.out.println;
    // here c The value of loses precision
    }
    }

//Idea Warning : Integer division in floating-point context
integer division in floating-point context

 Insert picture description here

5 Sonar Tips : Use “BigDecimal.valueOf” instead.

 resolvent : Use BigDecimal.valueOf() Instead of . Because this method internally converts parameters to String, Ensure the accuracy is not lost .

    public static BigDecimal valueOf(double val) {
        return new BigDecimal(Double.toString(val));
    }

6 Either re-interrupt this method or rethrow the “InterruptedException”.

 Insert picture description here
It is amended as follows :
 Insert picture description here

7 Do something with the “boolean” value returned by “delete”.

 Insert picture description here
 Insert picture description here
Prompt when the operation status code is included , The return value... Should not be ignored . In other words, the result of file deletion should not be ignored .
Therefore, the following modifications are made , However, the following modifications fix the vulnerability , But there's a new smell .
 Insert picture description here

Odor tips "java.nio.Files#delete" should be preferred (squid:S4042). You should use Files.delete() Method , Not between files delete. So it was finally revised to :
 Insert picture description here

8 Use a logger to log this exception.

 Insert picture description here
It is amended as follows :
 Insert picture description here

9 Unusual IllegalAccessException

java.lang.IllegalAccessException: Class com.study.reflect.ref_test.Tool can not access a member of class com.study.reflect.ref_test.Student with modifiers “private”
IllegalAccessException Indicates an exception without access .
Class com.study.reflect.ref_test.Tool can not access a member of class com.study.reflect.ref_test.Student with modifiers “private”
tool Class not accessible student Members of the .
This permission access is abnormal , It's because I didn't remove permission when I used violent reflection to obtain bytecode objects , That is to say setAccessible(true)

10 Use an “instanceof” comparison instead.

 Insert picture description here
It is amended as follows :
 Insert picture description here

11 Remove this throw statement from this finally block.

 Insert picture description here
explain : stay finally Block the use of return、break、throw Wait can inhibit try or catch Any unhandled thrown in the block Throwable Communication of , It is amended as follows :
 Insert picture description here

12 Remove this return statement from this finally block

 Insert picture description here
explain : because finally Write the inside return At the time of statement , It will be covered try In the code block return. because finally It will certainly be carried out . Examples are as follows :
 Insert picture description here
The above code is modified to :
 Insert picture description here

13 A “NullPointerException” could be thrown; “pkList” is nullable here.

 Insert picture description here
Add null value judgment , As shown below :
 Insert picture description here

14 Use try-with-resources or close this “ResultSet” in a “finally” clause.

 Insert picture description here
It is amended as follows :
 Insert picture description here
Or refer to the following :
 Insert picture description here
 Insert picture description here
Prompt that the resource is not closed , Need to be in finally Closing resources in , But turn off resources and put them in finally It is not standardized and has peculiar smell . So the recommended way to write it is to put the code that creates the resource flow in try() in , In this way, the system will automatically close resources , We don't need to write .close() Method , Pictured
 Insert picture description here

15 Use “Arrays.toString(array)” instead.

 Insert picture description here
It is amended as follows :
 Insert picture description here
Refer to the following
 Insert picture description here

16 Save and re-use this “Random”.

 Insert picture description here
explain : This hint is that random numbers should be reused , Then the reference he gave was like this
 Insert picture description here

17 Either re-interrupt this method or rethrow the “InterruptedException”.

 Insert picture description here
It is amended as follows
 Insert picture description here

18 Synchronize on a new “Object” instead.

 Insert picture description here
It is amended as follows
 Insert picture description here

19 Replace the call to “Thread.sleep(…)” with a call to “wait(…)”

 Insert picture description here
explain : If called when the current thread holds the lock Thread.sleep(…), This can lead to performance and scalability problems , Even worse , Because the execution of the thread holding the lock is frozen . The best of monitor Object call wait(…) To temporarily release the lock and allow other threads to run . It is amended as follows :

 Insert picture description here

20 Use “BigDecimal.valueOf” instead

 Insert picture description here
explain : Due to the imprecision of floating point , You are unlikely to come from BigDecimal(double) Get the expected value from the constructor . It is amended as follows :
 Insert picture description here

21 Call “Optional#isPresent()” before accessing the value.

 Insert picture description here
explain :Optional value You can save values , You can also not save . Values in optional methods can be used get() Method access , But it throws one
If there is no value , be NoSuchElementException. To avoid abnormality , Should always call get() Previous call isPresent() Method .
in addition , Please pay attention to other methods , Such as orElse(…)、orElseGet(…) or orElseThrow(…), Can be used to specify how to handle empty optional objects .

It is amended as follows :
 Insert picture description here

22 Use try-with-resources or close this “PreparedStatement” in a “finally” clause.

 Insert picture description here
Change it as follows : Use try-with-resources grammar
 Insert picture description here
Loophole

23 Make this “public static producer” field final

 Insert picture description here
It is amended as follows :
 Insert picture description here

24 Lower the visibility of this setter or remove it altogether.

 Insert picture description here
resolvent : Remove... From the enumeration set Method

25 Make this “public static redisTemplate” field final

 Insert picture description here
It is amended as follows :
 Insert picture description here

26 A “NullPointerException” could be thrown; “command” is nullable here.

 Insert picture description here
Null pointer , Solution : Judge first or instantiate first , Then access the properties or members .

27 Cast one of the operands of this multiplication operation to a “long”

explain :int The number operation finally turns the result into long It is possible to overflow
Solution : Convert to long Type budget

give an example :
long bigNum = Integer.MAX_VALUE + 2; // Noncompliant. Yields -2147483647

Replace with
long bigNum = Integer.MAX_VALUE + 2L;

28 Make this member “protected”.

 Insert picture description here
 Insert picture description here
terms of settlement

 Insert picture description here

29 Not enough arguments

 Insert picture description here
The one above bug Very common in projects , All parameters are used new Object[]{} encapsulated . Especially from class File decompiled java The file format is the same . But if we want to eliminate bug If so, just use parameters directly , Do not use new Object[]{} encapsulation .
 Insert picture description here

30 This branch can not be reached because the condition duplicates a previous condition in the same sequence of “if/else if” statements

if Two branches cannot be the same .
 Insert picture description here
Just delete the duplicate .

31 Make this “public static st_soTimeout” field final

 Insert picture description here
There's no good reason not to declare fields “final” In this case, declare the field “public” and “static”. Most of the time , This is an error sharing state between multiple objects . But in this way , Any object can do whatever it wants with the shared state , For example, set it to null .
solve

32 Make st_sendPort a static final constant or non-public and provide accessors if needed.

33 ‘PassWord’ detected in this expression, review this potentially hard-coded credential.

原网站

版权声明
本文为[qq_ thirty-seven million seven hundred and five thousand five h]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207062018469735.html