151 tips for improving Java programs--note one

Source: Internet
Author: User
Tags shallow copy

I. common methods and guidelines in Java development

1, do not appear in constants and variables easily confused letters

eg:long i=1l, this is one or lL , it is recommended to use uppercase way ;

2. Do not let constants become variables

eg:publicstatic final int rand_const=new Random (). Nextint ();

3, the type of ternary characters 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 let null values and null values threaten the variable length method

eg:methodA (String str,integer ... is);

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

Test:methoda ("China");

MethodA ("China", null);

6, overwrite the variable length method also must obey the rules

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

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

7. Beware of self-increasing traps

Eg:int count=0;for (int i=0;i<10;i++) {count=count++}; output is 0

8. Don't let the grammar bother you

Eg:goto statement,Methoda:methodb ();

9, less use static import

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

11, develop a good habit, explicitly declare the UID

Eg: Serialization

12. Avoid assigning values to invariants (final adornments ) in constructors with serialized classes

13. Avoid complex assignments for final variables

Eg:publicfinal String name=initname ();

Public String Initname () {return "Hello";}

When deserializing, the final variable is not re-assigned in the following cases:

1) Assign a value to the final variable through the constructor;

2) Assign a value to the final variable by the method return value;

3) Final modified properties are not basic types;

14. Use the private method of serialization class to solve the problem of partial attribute persistence skillfully

15, break must not forget

Switch....case ... .

16, variable business use scripting language to write

For example, using scriptengine in Java to invoke methods in JavaScript

17. Be cautious with dynamic compilation: Compile the . Java file directly during the run, execute the . Class, write the Java class information into the string, Then call the relevant interface to execute the Java information in the string during the run

18, avoid instanceof unintended results , pay attention to instanceof Set up the condition is that the left and right side of the operand to inherit or implement the relationship, or compile will error

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

19. Assertion is definitely not chicken:assert< boolean expression >:< error message >

20, do not replace only one class : prohibit the use of class file substitution method when publishing the application system, the whole war package release is the complete strategy

II. Basic Types

21, judge the odd even, with even judgment, without odd judgment

Eg:i%2==1?" Odd ":" even "; -1 will cause problems .

Correct use:i%2==0?" Even ":" Odd ";

22. Handling currencies with BigDecimal and shaping types

23, do not let the type of silent conversion

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

Long v=length_speed*60*8 will have negative numbers, because when calculating, first the operation is then the type conversion, the three number is the int type, after the calculation exceeds the int , so the calculated result is a negative value;

The right way:long v=1l*length_speed*60*8; The back of the calculation will be converted into a long plastic

24, the Shaping type boundary value needs to consider, when carries on the unit test, when carries on the int type parameter test, needs to consider the following several values:0, positive maximum, negative minimum

25, do not let the rounding loss of one side, for example, in the banking, financial related industries of the system, according to different scenarios, carefully select different rounding mode to improve the accuracy of the project, reduce the loss of the algorithm

26. Beware of the null value of the wrapper type : When the wrapper type participates in the operation, the null value check is done

27, the size of the careful packaging type comparison

Eg:integer a=new Integer (100);

Integer b=new integer (100);

a==b:false,a>b:false,a<b:false;

28, priority to use the plastic pool: the basic type of boxing action is throughvalueOfmethod to achieve theinttype is converted toIntegerobject, ifintthe range of values in-128to the127between, then it directly fromCachearray, not in the range of theinttype is passedNewgenerates wrapper objects, by wrapping the class'svalueOfgenerating wrapper instances can significantly improve spatial and temporal performance

29. Choose 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) {}

During automatic boxing, the base type can be widened before turning into a wide-type wrapper type, but not directly to a wide-type wrapper type. Int can be widened into Long type, and then turn into Long object, but not directly into Long object.

30, do not randomly set the seed of random numbers

Eg:random random=new Random (1000); the seed that produces the random number is fixed.

random number generated in Java:random,math.random ();

Iii. types of objects and methods

31, do not exist in the interface implementation of the code

Interface s{public void DoSomething ();} Interface b{s s=new S () {public void dos{}}

32, static variables must first be declared after the assignment

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

33, do not overwrite the static method, when a static method is defined in the parent class, the subclass should not overwrite the static method, the definition of static methods or properties in the class should be directly accessed through the class name, access to static methods or properties through the instance object is not a good habit;

34, the constructor should be as simple as possible, otherwise it may occur due to the initialization of variables inconsistent;

35. Avoid initializing other classes in the constructor

36, using the Construction Code block refining Program: The Construction code block will be executed in each of the different parameters of the construction method, first execute the construction code block, and then execute the construction method, it is not run before the constructor, it relies on the constructor execution, we can use the construction code block in the following scenario:1 : Initializes instance variable 2: initializes the instance environment;

37, constructs the code block will think you, in constructs the method uses this and the Super , constructs the code block already to consider for you, if uses in the parameter construction method the This () , the Construction code block will not be re-executed, so use it flexibly;

38, the use of static internal classes to enhance the packaging of classes and improve the readability of the Code

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

40, the anonymous class constructor is very special;

41, flexible use of internal classes, so that multiple inheritance into reality;

42. The best way to make the tool class non-instancing is : It is not possible to instantiate using the reflection mechanism

public class utils{

Private Utils () {

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

}}

43. Avoid shallow copies of objects :

The clone method provided by object is just a shallow copy, which means that it does not copy all of the properties of the object, but has a selective copy of the copy rule as follows:

Base type: Copies its value

Object: Copy the address reference, which means that the newly copied object shares the instance variable with the original object and is not restricted by access rights.

String : The copy is also an address, which is a reference, but when modified, it regenerates The new string from the string pool , and the original string object remains unchanged, where we can think String is a basic type.

44. It is recommended to use serialization to make copies of objects: Refer to my blog post, shallow copy and deep copy of Java objects:http://blog.csdn.net/harderxin/article/ details/41694747

45. Do not recognize yourself when you overwrite the Equals method ( See 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. Equals should consider a null value Scenario

The  second version----recommended 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. In order to prevent inheritance, it is recommended to use getclass for type judgment in equals instead of using instanceof

The  third version----recommended 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. Overwrite the equals method must overwrite the hashcode method:

HASHMAP:The underlying processing mechanism is saved as an arrayMapArticles(Map Entry), the key to this is the processing mechanism of the array subscript: based on the incoming elementhashcodeThe return value of the method determines the subscript of its array, if the array position already has aMapentries are not processed if they are equal to the passed-in key value, if not equal, if the array position has no entries, insert and add toMapin the list of entries, in the same vein, check that the key exists and determine the location based on the hash code, and then traverse the lookup key value. hashcodevalues that we can useOrg.apache.commons.lang.builderA hash code generation tool under the packageHashcodebuilderBuild

49, recommended to overwrite the ToString method:java provides the default ToString method is not friendly, print out only the machine can read, its format is the class name +@+hashcode, so it is recommended to overwrite the toString method so that we could debug

50, use the package-info class for the package service: in the need to use the package, you can consider this special class

51, do not actively garbage collection: in the application do not directly use System.GC () to actively recycle garbage, even if there is a frequent memory overflow and do not call

151 tips for improving Java programs--note one

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.