How to write a more standardized JAVA code

How to write code more standardized JAVA

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

When faced with multiple query conditions, 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" after the database system can not use an index such as query optimization strategy, the database system will be forced to scan each row of data (ie full table scan) to compare whether this line meet the filter condition,

When the large amount of data query speed table will be very slow; In addition, there is also the risk of SQL injection. (Solution adopted <where> tag), the UPDATE operation, too, may be used <set> tag in place of 1 = 1.

<select id="selectTypes" parameterType="map" resultMap="BaseResultMap">
    select
    type_id, type_name, company_id, updated_at, update_user
    from type
   <where>
       <if test="companyId != null and companyId != ''">
           company_id = #{companyId}
       </if>
       <if test="name != null and name != ''">
           and type_name like #{name}
       </if>
   </where>
    order by create_at desc
</select>

 

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

When the cycle just need to get Map key primary key, iteration keySet () is correct; however, when you need a primary key value and key value, the iteration entrySet () is a more efficient approach,

Than its first iteration keySet () and then go get the value through better performance.

反例:
//Map 获取value 反例:
HashMap<String, String> map = new HashMap<>();
for (String key : map.keySet()){
String value = map.get(key);
}
正例:
  //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, () detects whether empty there is no problem in the logic, but using Collection.isEmpty () makes the code more readable, better performance can be obtained;

In addition, any Collection.isEmpty () time complexity of implementation is O (1), multiple cycles need not traverse, but some of a Collection, by () method of time complexity implementation may be O (n ). O (1) number of cycles to latitude

反例:
LinkedList<Object> collection = new LinkedList<>();
if (collection.size() == 0){
  System.out.println("collection is empty.");
 }
正例:
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.

Anti Example: 
// Initialize the list, the list to add elements counter example: 
int [] = ARR new new int [] {1,2,3,4}; 
List <Integer> the ArrayList list = new new <> (); 
for (int I : ARR) { 
  List.add (I); 
} 
n Example: 
// initialize the list, add to list elements n Example: 
  int [] = ARR new new int [] {1,2,3,4}; 
  // specified the size of the capacity set list 
  List <Integer> the ArrayList list = new new <> (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.

Anti Example: 
// string concatenation in a loop counter example 
String STR = ""; 
for (int I = 0; I <10; I ++) { 
  // string concatenation will not be optimized Java in a loop 
  str + = i ; 
} 
n Example: 
// n string in a loop stitching Example 
 string str1 = "Love"; 
 string str2 = "Courage"; 
 string strConcat str1 + = str2; // the Java compiler string concatenation of the normal mode optimize 
  the StringBuilder the StringBuilder new new SB = (); 
  for (int I = 0; I <10; I ++) { 
     // in the cycle, Java compiler can not be optimized, so manually using the 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).

Anti Example: 
// frequent calls Collection.contains () trans Example 
List <Object> = new new List the ArrayList <> (); 
for (int I = 0; I <= Integer.MAX_VALUE; I ++) { 
  // time complexity of O ( n-) 
  IF (list.contains (I)) 
  System.out.println ( "List the contains" + I); 
 } 
n Example: 
// frequent calls Collection.contains () n Example 
  List <Object> list = new ArrayList <> (); 
  the Set <Object> = new new SET HashSet <> (); 
  for (int I = 0; I <= Integer.MAX_VALUE; I ++) { 
      // time complexity is O (. 1) 
      IF (set.contains (I )) { 
          System.out.println ( "List the 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.

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

Anti Example: 
// the type or other objects into a string counter example: 
int = 520. NUM; 
// "" + value 
String strLove = "" + NUM; 
Positive Example: 
// the type or other objects into n strings Example : 
int = 520. NUM; 
// String.valueOf () is more efficient 
String strLove = String.valueOf (num);

  Nine , 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.

反例:

// BigDecimal 反例BigDecimal bigDecimal = new BigDecimal(0.11D);
正例:

// BigDecimal 正例BigDecimal bigDecimal1 = bigDecimal.valueOf(0.11D);

 

 

 

 

  Ten, returns an empty array rather than null and collections

  If the program run returns null, the caller requires mandatory testing null, 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 in,

  You can also delete the caller detect null statement makes the code more concise. 

反例:
//返回null 反例
public static Result[] getResults() {
    return null;
}

public static List<Result> getResultList() {
    return null;
}

public static Map<String, Result> getResultMap() {
    return null;
}
正例:
//返回空数组和空集正例
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();
}

  Eleven, preferably used to determine the value or constant equals method invocation

equals method of Object readily shorting pointer exception, should be used with a constant value or determined object to call the equals method.

Anti Example: 
 // call the equals method counterexample 
private static boolean FileReader (String fileName) throws IOException { 
   // pointer exception shorting may 
   return fileName.equals ( "Charming"); 
 } 
n Example: 
// Example call n equals method 
private static boolean FileReader (String fileName) throws IOException { 

    // use constant values or determine object to call the equals method 
    return "Charming" .equals (fileName); 

    // or: java.util.Objects.equals () method 
   return objects. the equals ( "Charming", fileName); 
 }

  Original link: https: //www.cnblogs.com/taojietaoge/p/11575376.html

 

Guess you like

Origin www.cnblogs.com/lmqblogs/p/11752764.html