Enhance the JAVA code of good "taste"

Make the code more performance

 

If necessary Map the primary key and value should be iterative entrySet ()

 

When the cycle requires only Map primary key, iteration keySet () is correct. However, when you need a primary key and value, iterative entrySet () is a more efficient approach than the first iteration keySet () and then go get the value of better performance.

 

Counterexample:

 

 

Map<String, String> map = ...;for (String key : map.keySet()) {    String value = map.get(key);    ...}

 

Positive examples:

 

 

Map<String, String> map = ...;for (Map.Entry<String, String> entry : map.entrySet()) {    String key = entry.getKey();    String value = entry.getValue();    ...}

 

Should use Collection.isEmpty () detects empty

 

Use of a Collection, () detects no empty logical problem, but using Collection.isEmpty () makes the code more readable, better performance can be obtained. Any Collection.isEmpty () time complexity of implementation is O (1), but some time complexity of a Collection, () may be implemented in O (n).

 

Counterexample:

 

 

if (collection.size() == 0) {    ...}

 

Positive examples:

 

 

if (collection.isEmpty()) {    ...}

 

If desired be detected null, may be employed CollectionUtils.isEmpty (collection) and CollectionUtils.isNotEmpty (collection).

 

Do not pass their own collection of objects

 

In addition, some methods require parameters remain unchanged during the execution, so the collection passed to itself may result in unexpected behavior.

 

Counterexample:

 

 

List<String> list = new ArrayList<>();list.add("Hello");list.add("World");if (list.containsAll(list)) { // 无意义,总是返回true    ...}list.removeAll(list); // 性能差, 直接使用clear()

 

Try to specify the size of the set of initialization

 

 java collection class with a very convenient, but look at the source code can be seen, the collection also has size limitations. Each expansion is likely to be time complexity O (n), it is possible to specify a set of predictable size, can reduce the number of expansion set.

 

Counterexample:

 

 

int[] arr = new int[]{1, 2, 3};List<Integer> list = new ArrayList<>();for (int i : arr) {    list.add(i);}

 

Positive examples:

 

 

int[] arr = new int[]{1, 2, 3};List<Integer> list = new ArrayList<>(arr.length);for (int i : arr) {    list.add(i);

}

 

String concatenation use StringBuilder 

 

Generally the strings together at compile java will be optimized, but in a loop string concatenation, java compile-time optimization can not be done, so it is necessary to use StringBuilder to be replaced.

 

Counterexample:

 

 

String s = "";for (int i = 0; i < 10; i++) {    s += i;}

 

Positive examples:

 

 

String a = "a";String b = "b";String c = "c";String s = a + b + c; // 没问题,java编译器会进行优化StringBuilder sb = new StringBuilder();for (int i = 0; i < 10; i++) {    sb.append(i);  // 循环中,java编译器无法进行优化,所以要手动使用StringBuilder}

 

List of random access

 

We all know the difference between an array and a linked list: more efficient random access array. When you call a method to get List, if you want to randomly access the data, we do not know the internal array implementation is a linked list or array, how to do it? Can determine whether it implements * RandomAccess * interface.

 

Positive examples:

 

 



// 调用别人的服务获取到listList<Integer> list = otherService.getList();if (list instanceof RandomAccess) { // 内部数组实现,可以随机访问 System.out.println(list.get(list.size() - 1));} else { // 内部可能是链表实现,随机访问效率低}

 

Frequently called Collection.contains methods use the Set

 

In java class library collection, List contains the general method of time complexity is O (n), if a call to contains frequently find data in a code can be converted into a first list HashSet achieved, the O (n) time complexity degree reduced O (1).

 

Counterexample:

 

 

ArrayList<Integer> list = otherService.getList();for (int i = 0; i <= Integer.MAX_VALUE; i++) {    // 时间复杂度O(n)    list.contains(i);}

 

Positive examples:

 

 

ArrayList<Integer> list = otherService.getList();Set<Integer> set = new HashSet(list);for (int i = 0; i <= Integer.MAX_VALUE; i++) {    // 时间复杂度O(1)    set.contains(i);}

 

Make the code more elegant

 

Add after long integer constant capital L

 

When using the long integer constant value, the latter need to add L, must be uppercase L, not lowercase l, l lowercase easily confused with the number 1 and misleading.

 

Counterexample:

 

 

long value = 1l;long max = Math.max(1L, 5);

 

Positive examples:

 

 

long value = 1L;long max = Math.max(1L, 5L);

 

Do not use mana

 

When you write a piece of code, use mana may seem clear, but they do not appear when debugging so clear. This is why the magic value is defined as the reason can be read constants. However, -1, 0 and 1 are not considered mana.

 

Counterexample:

 

 

for (int i = 0; i < 100; i++){    ...}if (a == 100) {    ...}

 

Positive examples:

 

 

private static final int MAX_COUNT = 100;for (int i = 0; i < MAX_COUNT; i++){    ...}if (count == MAX_COUNT) {    ...}

 

 

Do not use collection implementation to assign a static member variables

 

For static member variables collection types, do not use the set to achieve the assignment, you should use static code block assignment.

 

Counterexample:

 

 

private static Map<String, Integer> map = new HashMap<String, Integer>() {    {        put("a", 1);        put("b", 2);    }};

private static List<String> list = new ArrayList<String>() { { add("a"); add("b"); }};

 

Positive examples:

 

 

private static Map<String, Integer> map = new HashMap<>();static {    map.put("a", 1);    map.put("b", 2);};

private static List<String> list = new ArrayList<>();static { list.add("a"); list.add("b");};

 

We recommend the use of try-with-resources statement

 

Java 7 introduced a try-with-resources statement, which can guarantee the resources to close, better than the original try-catch-finally statement, and make the program more concise code more secure.

 

Counterexample:

 

 

private void handle(String fileName) {    BufferedReader reader = null;    try {        String line;        reader = new BufferedReader(new FileReader(fileName));        while ((line = reader.readLine()) != null) {            ...        }    } catch (Exception e) {        ...    } finally {        if (reader != null) {            try {                reader.close();            } catch (IOException e) {                ...            }        }    }}

 

Positive examples:

 

 

private void handle(String fileName) {    try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {        String line;        while ((line = reader.readLine()) != null) {            ...        }    } catch (Exception e) {        ...    }}

 

 

Delete unused private methods and fields of

 

Delete unused private methods and fields, and make the code more concise and easier to maintain. If necessary re-use, it can be retrieved from the history of submission.

 

Counterexample:

 

 

public class DoubleDemo1 {    private int unusedField = 100;    private void unusedMethod() {        ...    }    public int sum(int a, int b) {        return a + b;    }}

 

Positive examples:

 

 

public class DoubleDemo1 {    public int sum(int a, int b) {        return a + b;    }}

 

 

Delete unused local variables

 

Delete unused local variables to make the code more concise and easier to maintain.

 

Counterexample:

 

public int sum(int a, int b) {    int c = 100;    return a + b;}

 

Positive examples:

 

 

public int sum(int a, int b) {    return a + b;}

 

Methods to remove unused parameters

 

The method parameter is not used misleading, delete unused method parameters, to make the code more concise and easier to maintain. However, since the method is a method to rewrite the parent class or interface defined based on, even if there is an unused parameter method, but also it can not be deleted.

 

Counterexample:

 

 

public int sum(int a, int b, int c) {    return a + b;}

 

Positive examples:

 

 

public int sum(int a, int b) {    return a + b;}

 

Delete unnecessary brackets expression

 

The corresponding expression extra brackets, it was thought to contribute code readers, some people feel totally unnecessary. For a people who are familiar with Java syntax, expressions extra parentheses would give the code is more complicated.

 

Counterexample:

 

 

return (x);return (x + 2);int x = (y * 3) + 1;int m = (n * 4 + 2);

 

Positive examples:

 

 

return x;return x + 2;int x = y * 3 + 1;int m = n * 4 + 2;

 

Tools should be shielded constructor

 

Is a collection of tools and functions pile static field, it should not be instantiated. However, Java adds an implicit public constructor for each class is not explicitly defined constructor. Therefore, in order to avoid java "white" incorrect use, you should explicitly defined to shield the private constructors implicit public constructor.

 

Counterexample:

 

 

public class MathUtils {    public static final double PI = 3.1415926D;    public static int sum(int a, int b) {        return a + b;    }}

 

Positive examples:

 

 

public class MathUtils {    public static final double PI = 3.1415926D;    private MathUtils() {}    public static int sum(int a, int b) {        return a + b;    }}

 

 

Remove the extra exception caught and thrown

 

After capturing an exception with catch phrase, nothing is processed, re-let an exception is thrown, this result is not like catching exceptions, you can delete or add another piece of code that process.

 

Counterexample:

 

 

private static String readFile(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;    }}

 

 

 

Positive examples:

 



private static String readFile(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(); }}

 

Public static constant access should be through the class

 

Although instances of access by public static class constants are allowed, but easy to mistake it for an instance of each class has a public static constant. Therefore, public static class constants should be directly accessible through.

 

Counterexample:

 

 

public class User {    public static final String CONST_NAME = "name";    ...}

User user = new User();String nameKey = user.CONST_NAME;

 

Positive examples:

 

 

public class User {    public static final String CONST_NAME = "name";    ...}

String nameKey = User.CONST_NAME;

 

Do not judge NullPointerException empty

 

Null pointer exception should avoid the code (such as detector is not empty), instead of processing the captured abnormal manner.

 

Counterexample:

 

 

public String getUserName(User user) {    try {        return user.getName();    } catch (NullPointerException e) {        return null;    }}

 

 

Positive examples:

 

 

public String getUserName(User user) {    if (Objects.isNull(user)) {        return null;    }    return user.getName();}

 

 

Use String.valueOf (value) instead of "" + value

 

When the type or other objects should be converted to a string, using String.valueOf (value) "" + is higher than the efficiency value.

 

Counterexample:

 

 

int i = 1;String s = "" + i;

 

Positive examples:

 

 

int i = 1;String s = String.valueOf(i);

 

 

@Deprecated obsolete code to add comment

 

When a piece of code out of date, but in order to be compatible and can not be directly deleted, you do not want someone to use it later, you can add annotations @Deprecated marked. @Deprecated add comments in the document to explain and offer alternatives.

 

Positive examples:

 

 

/** * 保存 * * @deprecated 此方法效率较低,请使用{@link newSave()}方法替换它 */@Deprecatedpublic void save(){    // do something}

 

Make the code away bug

 

Prohibit the use of the constructor 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.

 

Counterexample:

 

BigDecimal value = new BigDecimal(0.1D); // 0.100000000000000005551115...

 

Positive examples:

 

BigDecimal value = BigDecimal.valueOf(0.1D);; // 0.1

 

Returns an empty array instead of null and empty collection

 

Return null, the caller requires mandatory testing null, otherwise it will throw a null pointer exception. Returns an empty array or an empty set, effectively avoided because the caller does not detect null null pointer exception is thrown, you can also delete the caller detect null statement makes the code more concise.

 

Counterexample:

 

 

public static Result[] getResults() {    return null;}

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

public static Map<String, Result> getResultMap() { return null;}

public static void main(String[] args) { Result[] results = getResults(); if (results != null) { for (Result result : results) { ... } }

List<Result> resultList = getResultList(); if (resultList != null) { for (Result result : resultList) { ... } }

Map<String, Result> resultMap = getResultMap(); if (resultMap != null) { for (Map.Entry<String, Result> resultEntry : resultMap) { ... } }}

 

Positive examples:

 

 

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

public static void main(String[] args) { Result[] results = getResults(); for (Result result : results) { ... }

List<Result> resultList = getResultList(); for (Result result : resultList) { ... }

Map<String, Result> resultMap = getResultMap(); for (Map.Entry<String, Result> resultEntry : resultMap) { ... }}

 

Priority use to determine the value constant or to call the equals method

 

equals method of Object readily shorting pointer exception, should be used with a constant value or determined object to call the equals method. Of course, the use of java.util.Objects.equals () method is the best practice.

 

Counterexample:

 

 

public void isFinished(OrderStatus status) {    return status.equals(OrderStatus.FINISHED); // 可能抛空指针异常}

 

Positive examples:

 

 

public void isFinished(OrderStatus status) {    return OrderStatus.FINISHED.equals(status);}

public void isFinished(OrderStatus status) { return Objects.equals(status, OrderStatus.FINISHED);}

 

Enumerated attribute field must be private immutable

 

Enumeration is generally used as a constant, or if the common attribute field setting field enumeration methods exist, then the enumeration constant properties can easily be modified. Ideally, the attribute field enumeration is private and the private constructor assignment, there is no corresponding method Setter, preferably together with the final modifier.

 

Counterexample:

 

 

public enum UserStatus {    DISABLED(0, "禁用"),    ENABLED(1, "启用");

public int value; private String description;

private UserStatus(int value, String description) { this.value = value; this.description = description; }

public String getDescription() { return description; }

public void setDescription(String description) { this.description = description; }}

 

Positive examples:

 

 

public enum UserStatus {    DISABLED(0, "禁用"),    ENABLED(1, "启用");

private final int value; private final String description;

private UserStatus(int value, String description) { this.value = value; this.description = description; }

public int getValue() { return value; }

public String getDescription() { return description; }}

 

Be careful String.split (String regex)

 

String String split method, passing in the delimited string is a regular expression! Some of the keywords (such as [] () \ |., Etc.) need to be escaped.

 

Counterexample:

 

 

"a.ab.abc".split("."); // 结果为[]"a|ab|abc".split("|"); // 结果为["a", "|", "a", "b", "|", "a", "b", "c"]

 

Positive examples:

 

 

"a.ab.abc".split("\\."); // 结果为["a", "ab", "abc"]"a|ab|abc".split("\\|"); // 结果为["a", "ab", "abc"]

 

to sum up

 

This article can be said to be engaged in the development of Java lessons learned and share it out for your reference. We hope to help you avoid stepping pit, make the code more efficient and elegant.

 

@From: https://mp.weixin.qq.com/s/O3vj-Pcy6eCtw6p4dgcNdw

Guess you like

Origin www.cnblogs.com/breka/p/11651975.html