Java rules--intermediate articles

Source: Internet
Author: User
Tags add define object contains exception handling interface reference throwable
The description of the Java rules described in this article is divided into 3 major levels, the intermediate is usually developed with more than the level, in the future will be written in other rules. Following these rules can improve the efficiency of the program, make the code more readable, and so on.
(1) Turn off input or output resources in the Finally method
If the input or output stream is defined in the method body, it needs to be turned off in finally.
These kinds of 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 the next method returns without calling the Close () method to release the resources of input () and output (), a system resource leak can occur. And, in any case, be sure to call the close () method in all the returns, including when the exception occurs. So you need to add this method to the finally method. This ensures that resources are turned off under any circumstances.
Error Example:
public class CIO {
public void Method (Java.io.File f) {
Java.io.FileInputStream FIS = null;
try {
FIS = new Java.io.FileInputStream (f);
Fis.read ();
Fis.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, there is no guarantee that the resource is closed.
}
}
Revised Code:
public class Ciofixed {
public void Method (Java.io.File f) {
Java.io.FileInputStream FIS = null;
try {
FIS = new Java.io.FileInputStream (f);
Fis.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 (FIS!= null) {
try {
Fis.close ();
catch (Java.io.IOException e) {
SYSTEM.OUT.PRINTLN ("I/O Exception");
}
}
}
}
}

(2) Else pay attention to the problem.
It is generally thought that if the IF statement is only one sentence, then {} is not to be. However, if there is any else nesting, it is not the same, {} 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) No more catch () No code in the block
It is a good practice to put some error-handling code inside the catch () block. But if the catch () has code for Javadoc, that's OK.
Error Example:
try {
System.in.read ();
catch (Java.io.IOException e) {
Error
}

That's right:
try {
System.in.read ();
catch (Java.io.IOException e) {
SYSTEM.OUT.PRINTLN ("descriptive error");
}
Reference: Joshua Bloch: "Effective java-programming Language Guide".
Addison-wesley, 2001, pp. 187

(4) Do not enclose the value in the IF condition
If you do this, the system will report an error. It is unwise to use attached values in many Java conditional declarations, and the system also reports errors. can easily cause an exception. Compliance with the regulations can make maintenance simple and avoid inconsistencies.
Error Example:
if (b = true)
The correct:
if (b = = true)
Reference: Section 10.4 of http://java.sun.com/docs/codeconv/html/CodeConventions.doc9.html#547

(5) The For statement requires a loop body.
If {} is not, the For statement is only executed once!
Error Example:
for (i = 0; i < i++);
System.out.println (i);
Here print () is only performed once.
That's right:
for (i = 0; i < i++) {//FIXED
System.out.println (i);
}

(5) Do not define the method as main ().
In Java, the main () method is a special method. So do not define a method in the definition of such a name, so as not to cause mixed disturbances.

(6) Do not directly or indirectly define the ' Error ' and ' throwable ' subclasses
The ' Java.lang.Error ' overrides this method only when the JVM is abnormal, and if you define the class ' error ' by the direct or indirect class, it is pointed out that the error is internal to the JVM, not the class. So it's not visible to the Java compiler, so you can't check for incorrect exception handling.
' Java.lang.Throwable ' is ' Java.lang '. Exception ' and ' Java.lang.Error ' superior class, the user should inherit ' Java.lang if it is defined as an exception class. Exception '.
Example of an error: public class ABC extends error
Correct: public class ABC extends Exception

(7) The "case" problem in the "switch" statement
It is best to define a "return" or "break" in each "case" to control not to go to the "case" below. If a "case" statement does not have a "break" or "return" sentence at the end of the code, the program will go to the next. If this "case" is the last one, then there is no problem, and if there is a "case" behind it, it looks less secure.
Error Example:
switch (i) {
Case 1:
x = 10;
Break
Case 2:
x = 20;
Default
A = 40;
Break
That's right:
switch (i) {
Case 1:
x = 10;
Break
Case 2://violation
x = 20;
Break
Default
x = 40;
Break

(8) Do not recommend the use of ' system.getenv () '
It's not recommended to use ' system.getenv () ', which looks good, but not all systems have environment variables. Not using this method can also bring some inconvenience.
Error Example:
void method (String name) {
SYSTEM.GETENV (name); There are other ways to replace
}
If this method is not used, we can substitute it in other ways. For example: ' System.getproperty () ', ' gettypename () ', etc., this can also find the Java System Properties.
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. But different systems use different branch characters, so these characters violate Java platform independence in some sense.
Error Example:
System.out.println ("hello\n" + name);
We can substitute some other methods, such as println (), which play the same role on different system platforms. The latter recommends that everyone use this method: System.getproperty ("Line.separator")
Reference: David Flanagan: "Java in a Nutshell". O ' Reilly,
November 1999:third Edition, pp. 191-192

(10) Make all the inner classes "private".
Java allows a class to contain another class, with Java byte code without this concept. Class is interpreted by the compiler as a package-private class. In a deeper sense, any internal private object that contains a class can be accessed by an internal class, as well as by other classes within the same package.
Error Example:
public class INNER {
Class Inner_class {
void SetValue (int i) {
_value = i; Now the package will be accessible.
}
}
private int _value;
}
So you need to add private class Inner_class
Reference: Statically scanning Java code:finding security vulnerabilities.
John Viega, Gary McGraw, Tom Mutdosch, and Edward W. Felten
IEEE SOFTWARE September/october 2000

(11) Do not serialize the interface
If a byte array contains a serialized object. The attacker would be able to read the internal state of the object in the field (including private).
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.