151 suggestions for improving java programs-Note 1, java151-Note

Source: Internet
Author: User
Tags random seed

151 suggestions for improving java programs-Note 1, java151-Note

I. common methods and guidelines for Java Development

1. do not contain confusing letters in constants and variables.

Eg: long I = 1l. Is this 11 or lL? We recommend that you use uppercase letters;

2. Do not change constants into variables.

Eg: public static final int RAND_CONST = new Random (). nextInt ();

3. The three element types must be consistent.

Eg: String s = String. valueOf (I <100? 90: 100.0 );

4. Avoid method overloading with Variable Length Parameters

Eg: calPrice (int price, int discount );

CalPrice (int price, int... discounts );

5. Do not threaten the variable length method with null or null values.

Eg: methodA (String str, Integer... is );

MethodA (String str, String... strs );

Test: methodA ("China ");

MethodA ("China", null );

6. Override the variable length method should also follow the rules

Eg: parent: method (int price, int... discounts );

Children: method (int price, int [] discounts );

7. Be alert to the auto-increment trap

Eg: int count = 0; for (int I = 0; I <10; I ++) {count = count ++}; the output result is 0.

8. Do not confuse the syntax.

Eg: goto statement, methodA: methodB ();

9. Use less static Import

10. Do not overwrite static import variables and methods in this class.

11. develop good habits and explicitly declare UID

Eg: serialization

12. avoid assigning a value to the invariant (final modification) in the constructor using the serialization class.

13. Avoid complex assignment of final Variables

Eg: public final String name = initName ();

Public String initName () {return "hello ";}

Final variables are not re-assigned in the following circumstances during deserialization:

1) assign values to final variables through constructors;

2) assign a value to the final variable through the return value of the method;

3) The Final modified attributes are not of the basic type;

14. use private methods of serialization classes to cleverly Solve Partial attribute persistence Problems

15. Never forget Break

Switch... case ....

16. Easy-to-change businesses are written in scripting language

For example, using ScriptEngine in java to call methods in javascript

17. Use dynamic compilation with caution: Compile the. java file directly during running, execute. class, write java class information into the string, and then call the relevant interface to execute the java information in the string during running.

18. Avoid unexpected instanceOf results. Note that instanceOf must have an inheritance or implementation relationship between the left and right sides of the operand. Otherwise, an error will be reported during compilation.

Eg: 'A' instanceOf Character, new Date () instanceOf String,

19. assert is definitely not a problem: <Boolean expression >:< error message>

20. Do not replace only one class: the replacement of class files is forbidden when the application system is released. The release of the overall war package is the complete solution.

Ii. Basic Types

21. Judge the parity number, and use an even check. Do not use an odd check.

Eg: I % 2 = 1 ?" "Odd": "even";-1 may cause problems.

Correct use: I % 2 = 0 ?" Even ":" odd ";

22. Processing currency with BigDecimal and integer types

23. Do not change the type silently

Eg: public static final int LENGTH_SPEED = 30*10000*1000;

Long v = LENGTH_SPEED * 60*8 will show a negative number, because during the calculation, the first operation is performed before the type conversion, and the three numbers are all int type. After calculation, the maximum value of int is exceeded, therefore, the calculation result is negative;

The correct method: long v = 1L * LENGTH_SPEED * 60*8; During computation, the subsequent values are converted into long integers.

24. Consider the boundary values of the integer type. when testing the int type parameter during unit testing, consider the following values: 0, positive maximum, and negative minimum.

25. Do not turn off the loss of one party. For example, when conducting banking or financial-related industry systems, you must carefully select different rounding modes based on different scenarios, to improve project accuracy and reduce algorithm loss

26. Beware of null values of the packaging type: when the packaging type is involved in the calculation, the null value verification is required.

27. Careful packaging type size comparison

Eg: Integer a = new Integer (100 );

Integer B = new Integer (100 );

A = B: false, a> B: false, a <B: false;

28. Use Integer pool first: the basic type of packing is implemented through the valueOf method. For int type conversion to Integer object, if the int value range is between-128 and 127, then it is obtained directly from the cache array. If the int type is not in this range, a new packaging object is generated. Generating a packaging instance through the valueOf of the packaging class can significantly improve the space and time performance.

29. Select the basic type first.

Eg: int I = 0;

Test (I );

Test (Integer. valueOf (I ));

Public static void test (long I ){}

Public static void test (Long I ){}

In the process of automatic packing, the basic type can be widened first, and then changed to a wide type of packaging type, but cannot be directly converted to a wide type of packaging type. Int can be widened to the long type, and then converted to the Long object, but not directly to the Long object.

30. Do not set Random Seed.

Eg: Random random = new Random (1000); the seeds that generate Random numbers are fixed

Random numbers generated in Java: random, Math. Random ();

Iii. class objects and Methods

31. Do not have implemented code in the interface

Interface S {public void doSomething ();} interface B {S s = new S () {public void dos {}}}

32. Static variables must be declared first and then assigned a value.

Eg: static {I = 100;} public static int I = 1;

33. Do not override static methods. When a static method is defined in the parent class, do not override static methods in the subclass, defining static methods or attributes in a class should be directly accessed by class name, and accessing static methods or attributes through instance objects is not a good habit;

34. The constructor should be simplified as much as possible; otherwise, variable inconsistencies may occur during initialization;

35. Avoid initializing other classes in the constructor

36. constructor: constructor code blocks are executed once in the constructor of each parameter. The constructor code blocks are constructed before the constructor, it is not run before the constructor. It relies on constructor execution. We can apply the constructor code block to the following scenarios: 1. initialize instance variable 2: Initialize the instance Environment;

37. You may think about constructing a code block. When using this and super in the constructor, the constructor code block has been taken into consideration for you. If you use this () in a parameter constructor (), it will not re-execute to construct code blocks, so it should be used flexibly;

38. use static internal classes to enhance class encapsulation and improve code readability

39. Use the constructor of the anonymous class: new ArrayList () {}; new ArrayList (){{}{}{}}

40. The constructor of the anonymous class is special;

41. flexible use of internal classes to make multi-inheritance a reality;

42. The best way to make the tool class uninstantiated is: in this way, the reflection mechanism cannot be used for instantiation.

Public class Utils {

Private Utils (){

Throws new Error ("don't intstance me !!");

}}

43. Avoid copying objects:

The clone method provided by the Object is only a shortest COPY method. That is to say, it does not copy all the attributes of the Object, but is a selective copy. The copy rules are as follows:

Basic Type: copy the value.

Object: Copy address reference, that is, the newly Copied object shares the instance variable with the original object and is not restricted by access permissions.

String: A copy is also an address, which is a reference, but when it is modified, it will generate a new String from the String pool, the original String object remains unchanged, here we can consider String as a basic type.

44. The serialization method is recommended for object copying: refer to my blog post, java object copying and deep copy: http://blog.csdn.net/harderxin/article/details/41694747

45. do not recognize yourself when overwriting the equals method (see the code)

// Public boolean equals (Object obj) {// if (obj instanceof Person3) {// Person3 p = (Person3) obj; // remove trim () // return name. equalsIgnoreCase (p. getName (). trim (); //} // return false ;//}

46. null values should be considered for equals.

// Version 2 ---- 46 /// @ Override // public boolean equals (Object obj) {// if (obj instanceof Person3) {// Person3 p = (Person3) obj; // if (p. getName () = null | name = null) {// return false; //} else {// return name. equalsIgnoreCase (p. getName (). trim (); //} // return false ;//}

47. To prevent inheritance, we recommend that you use getClass in equals for type determination, instead of using instanceOf

// Version 3 ---- 47 @ Overridepublic boolean equals (Object obj) {if (obj! = Null & obj. getClass () = this. getClass () {Person3 p = (Person3) obj; if (p. getName () = null | name = null) {return false;} else {return name. equalsIgnoreCase (p. getName (). trim () ;}} return false ;}

48. Override the hashcode method for the equals method:

HashMap: The underlying processing mechanism stores Map entries in arrays. The key of this mechanism is the processing mechanism of the underlying objects of this array: the subscript of the array is determined based on the return value of the input element hashCode method. If a Map entry already exists in the array and is equal to the input key value, it is not processed, if they are not equal, they will be overwritten. If there are no entries in the array position, they will be inserted and added to the linked list of Map entries. Similarly, check whether the key exists based on the hash code to determine the position, then, retrieve the key value. We can use a hash code generation tool HashCodeBuilder under the org. apache. commons. lang. builder package to generate the HashCode value.

49. It is recommended to overwrite the toString method. The default toString method provided by java is unfriendly and can only be understood by the machine. The format is class name + @ + hashCode, therefore, we recommend that you override the toString Method for debugging.

50. Use the package-info class to serve the package: consider this special class when you need to use the package.

51. Do not take the initiative to recycle garbage: do not directly use System. gc () in the application to take the initiative to recycle garbage, even if there is frequent memory overflow, do not call

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.