Excerpt: Intermediate rule writing in Java

Source: Internet
Author: User

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

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.