Writing efficient Java programs-programming specifications

Source: Internet
Author: User
Basic

 

The description of Java rules described in this article is divided into five levels. Level 1 is the most basic and important level, and other rules will be written in the future. Following these rules can improve the program efficiency and make the code more readable.


 

(1) avoid using the new keyword to create a String object.
Copying a string constant to a String object is usually redundant and time-consuming.
Public class test {
Public void method (){
System. Out. Print (STR );
}
Private string STR = new string ("1"); // It is unnecessary to create a new object.
Private string str2 = "2" // this should be the case
}
Reference: Joshua Bloch: "valid Java-programming language guide"

(2) Avoid unnecessary nesting.
Excessive nesting can complicate your code and reduce readability.
Public class test {
String add (){
Int c = (a = a + B) + B; // too complex
Return C
}

}

Reference: http://java.sun.com/docs/codeconv/html/CodeConventions.doc9.html#177

(3) avoid declaring multiple variables of different types in the same row
This will make the program clearer and avoid confusion.
Private int index, index1 [];
The correct method should be as follows:
Private int index;
Private int index1 [];

Reference: http://java.sun.com/docs/codeconv/html/CodeConventions.doc5.html#2992

(4) write a statement in each row
This rule does not include for statements, such as 'For (INT I = 0; I <10; I ++) x --;', which can increase the readability of the Code.
Public class ospl {
Int method (int A, int B ){
Int I = a + B; return I; // poor readability
}
Correct:
Public class osplfixed {
Int method (int A, int B ){
Int I = A + B;
Return I;
}
}
Reference: section 7.1 of http://java.sun.com/docs/codeconv/html/CodeConventions.doc6.html#431

(5) Super. Finalize () is often called from finalize ()
Finalize () is called by Java during garbage collection, which is different from finally. If your parent class does not define finally (), you should also call it. There are two reasons: (1) You can add the finally method of the parent class to your class without changing the code. (2) In the future, you will get used to calling the finally method of the parent class, even if the parent class does not define the finally method.
The correct method should be as follows:
Public class parentfinalize {
Protected void finalize () throws throwable {
Super. Finalize (); // fixed
}

Reference: "The Java programming language" by Ken Arnold and James Gosling, page 49.

(6) do not log off listeners in finalize ().
Do not deregister listeners in the finalize () method. Finalize () is called only when no object is referenced. If listeners is removed from the finalize () method, finalize objects will not be removed from garbage collection.
Public void finalize () throws throwable {
Bbutton. removeactionlistener (Act );
}

(7) do not explicitly call the finalize () method
Although explicitly calling this method can ensure that you call it, it will be collected again after the method is collected.

Public class T7 {public void finalize () throws throwable {close_resources (); super. finalize ();} public void close_resources () {}} class test {void cleanup () throws throwable {t71.finalize (); // call t71 = NULL ;} private t71 = new T7 ();}

For such a call, we should create a release method by ourselves to do what was initially done by finalize (). Each time you want to explicitly call finalize () the release method is actually called. Then, use a judgment field to make sure that this method is only executed once. It does not matter if you call it later.

Public class T7 {public synchronized void release () throws throwable {If (! _ Released) {close_resources (); // do what the old 'finalize () 'Did _ released = true ;}} public void finalize () throws throwable {release (); super. finalize ();} public void close_resources () {} private Boolean _ released = false;} class testfixed {void closetest () throws throwable {t71. release (); // fixed t71 = NULL;} private T7 t71 = new T7 ();}

Reference: Nigel Warren, Philip BISHOP: "Java in practice-Design Styles and idioms
For valid tive Java ". Addison-Wesley, 1999. pp.110-111

(8) do not use APIs that are not recommended
Try to use the APIS recommended by jdk1.3. Many methods in classes, methods, or Java components are outdated or optional. Some methods sun uses the "deprecated" mark. It is best not to use the following example:
Private list t_list = new list ();
T_list.additem (STR );
If you check javadoc, we recommend that you use add () instead of additem ().
Reference: http://java.sun.com/j2se/1.3/docs/api/index.html

(9) create a 'serialversionuid' for all serialized classes'
You can avoid damaging the sequence compatibility from different classes. If you do not specify a uid, the system automatically generates a UID (based on the content of the class ). If the UID changes in your new version of the class, you cannot deserialize the old version even if the serialized class does not change.

Public class duid implements java. Io. serializable {public void method (){}}
Add a uid in it. When the serialization form of this class changes, you can also change this uid.

Public class duidfixed implements java. Io. serializable {public void method () {} Private Static final long serialversionuid = 1 ;}

Reference: Joshua Bloch: "valid Java-programming language guide"
Addison Wesley, 2001, pp. 223

(10) definition of private Constants
It is better to add the final mark to such a constant, so that the constant will not change from initialization to the final end value.
Private int size = 5;
The changed method is as follows:
Private Final int size = 5;

(11) avoid defining local variables and parameters of the method with the same name as class variables.
This can easily cause confusion. We recommend that you define any variable word as unique. In this case, those questions in scjp won't be used in reality :)

Public void method (Int J) {final int I = 5; // violation} private Int J = 2;

Suggestion:
Public void method (INT J1) {final int I = 5; // violation} private Int J = 2;

Intermediate

 

The description of the Java rules described in this article is divided into three main levels. The intermediate level is usually used for development, and other rules will be written in the future. Following these rules can improve the program efficiency and make the code more readable.
(1) disable the input or output Resources in the finally method.
If the input or output stream is defined in the method body, you need to disable it in finally.
The following calls do not need to follow this rule because the colse () method does not work :)
Java. Io. stringwriter java. Io. bytearrayoutputstream java. Io. bytearrayinputstream
If you do not call the close () method to release the input () and output () resources when returning the method, a system resource is leaked. In addition, in any case, make sure that the close () method is called in all the returned results, including when an exception occurs. Therefore, you must add this method to the finally method. This ensures that resources are disabled under any circumstances.
Error example:
Public class CIO {
Public void method (Java. Io. File f ){
Java. Io. fileinputstream FCM = NULL;
Try {
FS = new java. Io. fileinputstream (f );
FS. Read ();
FCM. Close ();
} Catch (Java. Io. filenotfoundexception E1 ){
System. Out. println ("file not found ");
} Catch (Java. Io. ioexception E2 ){
System. Out. println ("I/O exception ");
}
// If an exception occurs, the resource cannot be closed.
}
}
Corrected code:
Public class ciofixed {
Public void method (Java. Io. File f ){
Java. Io. fileinputstream FCM = NULL;
Try {
FS = new java. Io. fileinputstream (f );
FS. Read ();
} Catch (Java. Io. filenotfoundexception E1 ){
System. Out. println ("file not found ");
} Catch (Java. Io. ioexception E2 ){
System. Out. println ("I/O exception ");
} Finally {
If (FS! = NULL ){
Try {
FCM. Close ();
} Catch (Java. Io. ioexception e ){
System. Out. println ("I/O exception ");
}
}
}
}
}


 

(2) else considerations.
Generally, if the if statement has only one sentence, then {} is optional. However, if else nesting exists, it will be different. {} is required.
Error example:
If (I <5)
If (I <2)
I ++;
Else
I --;
After modification:
If (I <5 ){
If (I <2)
I ++;
}
Else {
I --;
}

(3) do not put any code in catch () blocks.
It is a good habit to put some error handling code in the catch () block. However, if the catch () contains javadoc code, it is also possible.
Error example:
Try {
System. In. Read ();
} Catch (Java. Io. ioexception e ){
// Error
}

Correct:
Try {
System. In. Read ();
} Catch (Java. Io. ioexception e ){
System. Out. println ("descriptive error ");
}
Reference: Joshua Bloch: "valid Java-programming language guide ".
Addison-Wesley, 2001, pp. 187

(4) do not include a value in the IF condition.
In this case, the system reports an error. It is unwise to use values in many condition declarations in Java, and the system will report errors. It is easy to cause exceptions. Compliance with this rule can simplify maintenance and avoid inconsistencies.
Error example:
If (B = true)
Correct:
If (B = true)
Reference: section 10.4 of http://java.sun.com/docs/codeconv/html/CodeConventions.doc9.html#547

(5) The for statement must be a loop body.
If no {} exists, the for statement will be executed only once!
Error example:
For (I = 0; I <10; I ++ );
System. Out. println (I );
Print () is executed only once.
Correct:
For (I = 0; I <10; I ++) {// fixed
System. Out. println (I );
}

(5) do not define the method as main ().
In Java, the main () method is a special method. Therefore, do not define such a name when you define a method to avoid confusion.

(6) do not directly or indirectly define the subclasses of 'error' and 'throwable '.
'Java. lang. error 'Only overwrites this method when JVM exceptions occur. If you define a class that inherits the class 'error' directly or not, it indicates that the error is internal to JVM, instead of this class. Therefore, it is invisible to the Java compiler, so that the error exception handling cannot be checked.
'Java. lang. throwable 'is 'java. lang. exception 'and 'java. lang. the upper-level class of 'error'. If you define an exception class, you should inherit 'java. lang. exception '.
Error example: Public Class ABC extends Error
Correct: Public Class ABC extends exception

(7) "case" in the "Switch" Statement
It is best to define a "return" or "break" in each "case" to control the possibility of not going into the "case" below. If a "case" statement does not have a "break" or "return" at the end of the Code, the program will go to the next "case ". If this "case" is the last one, then there will be no problem. If there is a "case" behind it, it will seem insecure.
Error example:
Switch (I ){
Case 1:
X = 10;
Break;
Case 2:
X = 20;
Default:
A = 40;
Break;
Correct:
Switch (I ){
Case 1:
X = 10;
Break;
Case 2: // Violation
X = 20;
Break;
Default:
X = 40;
Break;

(8) do not use 'System. getenv ()'
We do not recommend using 'System. getenv () '. This method looks very useful, but not all systems have environment variables. This method may be inconvenient.
Error example:
Void method (string name ){
System. getenv (name); // you can use other methods instead.
}
If this method is not used, we can use other methods instead. For example: 'System. getproperty () ', 'gettypename ()', etc. You can also find the Java System attribute.
Reference: David FLANAGAN: "Java in a nutshell". O' Reilly
November, 1999: Third Edition, pp.190-192

(9) do not use '/N' or'/R' to Branch
These two tags seem to be common, especially '/N '. We often use it as a branch. However, different systems use different branch characters, so these characters violate Java's platform independence in some sense.
Error example:
System. Out. println ("Hello/N" + name );
We can use other methods, such as println (), which play the same role on different system platforms. This method is recommended for the latter: system. getproperty ("line. separator ")
Reference: David FLANAGAN: "Java in a nutshell". O' Reilly,
November 1999: Third edition, pp. 191-192

(10) Make all internal classes "private ".
Java allows a class to contain another class without the concept of JAVA byte code. The class is interpreted by the compiler as a package-private class. To a deeper level, any internal private objects containing classes that can be accessed by internal classes can also be accessed by other classes in the same package.
Error example:
Public class inner {
Class inner_class {
Void setvalue (int I ){
_ Value = I; // now the package can be accessed.
}
}
Private int _ value;
}
Therefore, you need to add private class inner_class
See statically scanning Java code: finding security vulnerabilities.
John visch, Gary McGraw, Tom mutdosch, and Edward W. Felten
IEEE software September/October 2000

(11) do not serialize Interfaces
If a byte array contains a serialized object. Attackers can read the internal state merging fields (including private ones) of the object ).
Error example:
Public interface sample extends java. Io. serializable

Development

The description of the Java rules described in this article is divided into three main levels. This article abandons the situations rarely encountered during development, and those that are rarely used will appear in the advanced Article later. There are also six useful questions about string in international software development. complying with these rules can improve program efficiency and make code more readable.
(1) If a JDBC connection is not closed, disable it in the "finally" method.
If the database connection fails or the connection is not released, it seems irrelevant. However, other users need to wait for a longer period of time to connect, so that the database utilization efficiency will decrease. Make sure that your code releases the database connection in any situation, including errors or program termination exceptions. Disable the connection in the "finally" method to ensure this.
Error example:
Try {
Statement stmt = con. createstatement ();
} Catch (sqlexception e ){
E. printstacktrace ();
}
Correct example:
Try {
Statement stmt = con. createstatement ();
} Finally {
If (con! = NULL &&! Con. isclosed ()){
Con. Close ();
}
}

 

 

(2) avoid using the 'thread. Resume () ', 'thread. Stop ()', 'thread. Suspend () ', and 'runtime. runfinalizersonexit ()' methods.
These methods are also useful in normal development or textbooks, but these methods may lead to four locks. I have enough information to explain why the above method is not recommended.
Reference: 1. "Java. Lang. Thread" in the jdk api documentation
2. http://java.sun.com/j2se/1.3/docs/guide/misc/threadPrimitiveDeprecation.html
3. Paul HYDE: "Java thread programming"
Sams, ISBN: 0-672-31585-8 pp. 270

(3) Replace L with L when it represents a long integer constant.
Because l is easy to mix with 1.
Error example:
Long temp = 23434l;
Correct example:
Long temp = 23434l;
Reference: Ken Arnold, James Gosling: "The Java programming language Second Edition" Addison Wesley, 1997, pp.108

(4) It is best to write a comment at the beginning of JSP
Write a comment on the JSP file header to help others understand your code. This rule applies not only to JSP, but also to any development document.
Correct example: <% -- JSP comment -- %>

(5) Initialize all fields in a constructor class.
Because fields without initialization are a potential bug, it is best to initialize all fields in the class. In particular, it is best to assign an initial value to a static field at the beginning.
Error example:
Public class CSI {
Public CSI (){
This (12 );
K = 0;
}

Public CSI (INT Val ){
J = val;
}

Private int I = 5;
Private Int J;
Private int K;
}

Correct example:
Public class csifixed {
Public csifixed (){
This (12 );
}

Public csifixed (INT Val ){
J = val;
K = 0;
}

Private int I = 5;
Private Int J;
Private int K;
}
Reference: http://www.ambysoft.com/javaCodingStandards.pdf

(5) Suggestion for International Development: logical operators should not start or end with a single character
Do not use logical operators before and after a single character, if the code is to run in a country environment. We can use character comparison methods, which use unified character comparison standards to define character attributes.
Error example: public class clo {
Public Boolean isletter (char ch ){
Boolean _ isletter = (CH> = 'A' & Ch <= 'Z') // Error
| (CH> = 'A' & Ch <= 'Z ');
Return _ isletter;
}
}

Correct example:
Public class clofixed {
Public Boolean isletter (char ch ){
Boolean _ isletter = character. isletter (CH );
Return _ isletter;
}
}
Reference: http://java.sun.com/docs/books/tutorial/i18n/intro/checklist.html
For more character comparison methods, see: http://java.sun.com/docs/books/tutorial/i18n/text/charintro.html

(6) International Development Suggestion: Do not use 'date. tostring () 'For date objects ()'
Do not use the 'date. tostring () 'method. The date format is different for countries with different regions and languages. Do not use it.
Error example: The 'dateformat' class provides a predefined format type to specify the local format.
Public void printtoday (){
Date today = new date ();
String todaystr = today. tostring ();
System. Out. println (todaystr );
}
Correct example:
Public void printtoday (){
Locale currentlocale = locale. getdefault ();
Dateformat dateformatter = dateformat. getdateinstance (
Dateformat. Default, currentlocale );
Date today = new date ();
String todaystr = dateformatter. Format (today );
System. Out. println (todaystr );
}
Reference: http://java.sun.com/docs/books/tutorial/i18n/intro/checklist.html
Http://java.sun.com/docs/books/tutorial/i18n/format/dateFormat.html

(7) International Development Suggestion: Do not use the 'tostring () 'Method For numeric Variables
In global development, do not use the 'tostring () 'Method For numeric variables. It is applicable to any subclass of Java. Lang. Number. Including: bigdecimal, biginteger, byte, double, float, integer, long, and short. In this case, Java also defines the "numberformat" Method for formatting.
Error example:
Public class CNT {
Public void method (double amount ){
String amountstr = amount. tostring ();
System. Out. println (amountstr );
}
}
Correct example:
Public class ntsfixed {
Public void method (double amount ){
Locale currentlocale = locale. getdefault ();
Numberformat numberformatter =
Numberformat. getnumberinstance (currentlocale );
String amountstr = numberformatter. Format (amount );//
System. Out. println (amountstr + ''+ currentlocale. tostring ());
}
}
Reference: http://java.sun.com/docs/books/tutorial/i18n/intro/checklist.html
Http://java.sun.com/docs/books/tutorial/i18n/format/numberFormat.html

(8) International Development Suggestion: Do not use the 'string. Equals () 'Method
We recommend that you do not use the 'string. Equals () 'method, because it is not necessarily compared according to the relevant sequence in the unified character comparison standard. The pre-defined sorting rules provided by 'collator' are used to sort strings. The collator class calls the 'getinstance () 'method. Generally, a collator can be created locally by default. For example, collator mycollator = collator. getinstance (); you can specify a special locale when creating collator. Example: collator myfrenchcollator = collator. getinstance (locale. french); then you can call 'collator. compare () 'to execute a local character comparison mycollator. compare (S1, S2); learn more about the collator class: http://java.sun.com/docs/books/tutorial/i18n/text/collationintro.html

 

Error example:
Public class se {
Public Boolean compstr (string S1, string S2 ){
Boolean B = (s1.equals (S2 ));
Return B;
}
}
Correct example:
Public class sefixed {
Public Boolean compstr (string S1, string S2 ){
Collator mycollator = collator. getinstance ();
Boolean B = (mycollator. Compare (S1, S2) = 0 );
Return B;
}
}

Reference: http://java.sun.com/docs/books/tutorial/i18n/intro/checklist.html
Http://java.sun.com/docs/books/tutorial/i18n/text/locale.html

(9) International Development Suggestion: Do not use the 'stringtokenizer () 'Method
Error example: stringtokenizer ST = new stringtokenizer (STR );
You can get more information from here :'
Reference: http://java.sun.com/docs/books/tutorial/i18n/intro/checklist.html

(10) International Development Suggestion: Do not use the 'time. tostring () 'Method
Because the time format varies with different countries. If you use the date format class, your application will be able to correctly display the time and date in various places in the world. First, use the 'gettimeinstance () 'method to create a formatter. Then, call the 'format () 'method.
Error example:
Public class TTS {
Public void printtime (time t1 ){
String timestr = t1.tostring ();
System. Out. println (timestr );
}
}
Correct example:
Import java. SQL. time;
Import java. Text. dateformat;
Import java. util. locale;

Public class ttsfixed {
Public void printtime (time t1 ){
Dateformat timeformatter = dateformat. gettimeinstance (
Dateformat. Default, locale. getdefault ());
String timestr = timeformatter. Format (T1 );
System. Out. println (timestr );
}
}

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.