Java rules

xiaoxiao2021-03-06  38

JAVA basic rules of articles: flyingwcy Views: 212 Time: 2004-3-13 Reprinted from: Description JAVA Java Research Organization rules described in this article is divided into five levels, Level 1 is the most basic and most important level in the future Other rules will be written in successive. Comply with these rules can improve the efficiency of the program, so that the code has better readability. (1) Avoid using the new keyword to create a String object. Pubing a String constant Copy to String object is usually a lot of depth, waste time public class test {public void method () {system.out.print (STR);} private string str = new string ("1"); // Here the new object is completely unnecessary private strup str2 = "2" // correctly, this} Reference: Joshua Bloch: "Effective Java - Programming Language Guide" (2) Avoid using unnecessary nested. Excessive nesting will make your code complicate and weaken readability. Public class test {string add () {int C = (a = a b) b; // is too complex Return C}} reference: http://java.sun.com/docs/codeconv/html/codeconventions. Doc9.html # 177 (3) Avoiding multiple variables in the same line to declare different types of variables make the program more clear, avoid confusion private int index, index1 []; correct, this: 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 statement: for example:'for (int " I = 0; i <10; i ) x -; 'Can increase the readability of the code. Public class ospl {int method (int A, int b) {INT i = a b; returni; // readable is not strong} 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/codec/html/codeconventions.doc6.html# 431 (5) often call Super Ze () SUPER .finalize () Finalize () here is called when the garbage collection is carried out, and Finally is different. If your parent class does not define Finally (), you should also call. Here are two reasons: (1) Can add the Finally method of the parent class to your class without changing the code. (2) After you will develop a FINALLY method of habit to call the parent class, even if the parent class does not define the finally method.

The correct way should be so: 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 out in Finalize () Do not repay listners in the femitize () method, Finalize () is only called when there is no object reference, if listener removes from the Finalize () method, will not be in the garbage Remove in the collection. Public void finalize () throws throwable {bbutton.removeactionListener (ACT);} Do not explicitly call Finalize () Method Although this method allows you to make sure your call, but after this method collected The garbage collection will collect again. 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 calls We should create a release method, do things made by Finalize (), when you want to explicitly call finalize () The release method is actually called. Then use a judgment field to ensure that this method is only executed once, and it is not related to the call. public class T7 {public synchronized void release () throws Throwable {if {close_resources () (_released!); // 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 Effective Java". Addison-Wesley, 1999. PP.110-111 (8) Do not use unvice API Try to use the JDK1.3 recommended API. There are many ways to be old or optional in classes and methods or Java components. There are some method sun to use the "Deprecated" tag.

It is best not to use, for example: private list t_list = new list (); t_list.additem (STR); if Javadoc is checked, it will be found to replace AddItem (). Reference: http://java.sun.com/J2SE/1.3/docs/api/index.html (9) Creating a'SerialVersionuid'SerialVersionuid'SerialVersionuid'SerialVersionuid'SerialVersionuid'Serial attemption can avoid compatibility from your various types of destruction sequences Sex. If you don't specifically develop a UID, then the system generates a UID (according to the contents of the class). If the UID changes in your new version of the class, even if the serialized class has not changed, you can't reach the old version. Public class duid imports java.io.serializable {public void method () {}} adds a UID, when this class is changed, you can change this UID. public class DUIDFixed implements java.io.Serializable {public void method () {} private static final long serialVersionUID = 1;} Reference:. Joshua Bloch: "Effective Java - Programming Language Guide" Addison Wesley, 2001, pp 223 (10) A better way to define the Private constant is to add a Final tag for such constants, which will not change from initialization to the final end value. Private int size = 5; After changing the practice is: private final int size = 5; (11) Avoid the same name as the local variable and parameters are defined as the class variable. This is easy to cause sink, it is recommended to define any variable characters as unique. In this way, those topics in scjp can not 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; Reference: Michael Daconta, Eric Monk, J Keller, Keith Bohnenberger: "Java Pitfalls" John Wiley & Sons, ISBN: 0-471-36174-7 pp.17 - 25 JAVA Intermediate rule of articles: flyingwcy Views: 89 time: 2004-3-13 reprinted from: Description JAVA Java Research organization rules described in this article is divided into three main levels, with intermediate is usually more developed Multi-level, will write other rules in the future. Compliance with these rules can improve the efficiency of the program, so that the code is better and more readable. (1) Turn off the Input or Output resource in the finally method define the input or Output stream, you need to turn it off in Finally.

The following calls do not need to comply with this rule, because the colse () method does not work :) java.io.stringWriter Java.io.byteArrayoutputStream java.io.byterrayinputStream If the method is returned, there is no close () method To release the resources of Input () and Output (), it will cause a system resource leak. And under any circumstances, it is determined that the close () method is returned, including an exception. So this method needs to be added in the Finally method. This ensures that the resources will be closed in any case. Error example: public class cio {public void method (java.io.file f) {java.io.fileinputstream FII = null; try {fis = new java.io.fileinputStream (f); f); f); f); fis.read (); fis. Close ();} catch (java.io.filenotfoundexception e1) {system.out.println ("File Not Found");} catch (java.io.Excection E2) {system.out.println ("I / O Exception ");} // If an exception occurs, it will not guarantee the closing resource. }} Corrected code: public class ciofixed {public void method (java.io.file f) {java.io.fileinputstream fis = null; try {fis = new java.io.fileinputStream (f); f); f) );} catch (java.io.filenotfoundexception e1) {system.out.println ("file not found");} catch (java.io.Exception E2) {system.out.println ("I / O Exception") Finally {if (fis! = null) {Try {fis.close ();} catch (java.io iexception e) {system.out.println ("I / O Exception");}}}}} (2) Else's attention problem. Generally always thought that if the IF statement is only one sentence, then {} is not possible. However, if the if if if there is an else nest, {} is an essential error example: IF (i <5) IF (i <2) i ; ELSE I -; Modified: IF (i <5) {IF (i <2) i ;} else {i ---;} (3) Do not catch what code in the Catch () does not place some error handling code in the catch () block is a good habit. But if there is code about Javadoc, it is possible to Catch ().

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: "Effective Java - Programming Language Guide". Addison-Wesley, 2001, PP. 187 (4) Do not attach the value in the IF condition If the system will report an error. There is very uncommon to use the added value in Java, and the system will also report errors. It is easy to cause an exception. Compliance with this rule can make maintenance simply, avoid inconsistency. 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 requires a cyclic body. If there is no {}, the for statement will only be executed once! Error example: for (i = 0; i <10; i ); system.out.println (i); here print () only executes once. Correct: for (i = 0; i <10; i ) {// fixed system.out.println (i);} (5) Do not define the method into main (). In Java, the main () method is one Special method. So don't define such names when you define methods, so as not to cause sink. (6) Do not directly or indirectly define the subclass of'RROR' and 'THROWABLE''java.lang.Error' to override this method only when JVM occurs abnormally, if you define a direct or unstoppable class inherited the class Eerror', also pointed out that this error is inside the JVM, not this class. Therefore, it is invisible for the Java compiler, so that the error is handled. 'Java.lang.throwable' is'java.lang.exception' and'java.lang.Error''s superioclass, users should inherit 'Java.lang.exception' if you define an exception class. Error example: public class abc extends error correct: Public Class ABC EXTENDS Exception (7) The "Case" question inside "Switch" statement is best defined in each "copy" or "Break" to control Don't go to the "Case" below. If a "case" statement does not have a "BREAK" or "return" sentence in the code, the program will go to the next "case". If this "case" is the last one, then there is no problem. If there is "case" behind it, it is not safe.

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 : // violanch x = 20; Break; default: x = 40; Break; (8) Never use'system.Getenv () 'Not recommended to use'system.Getenv ()', this method looks very easy, However, not all systems have environment variables. It may also bring some inconvenience without this method. Error example: void method (string name) {system.Getenv (name); // You can use other methods} If this method is not used, we can replace it with other methods. For example:'System.getProperty () ','gettypename (), etc., which 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 very Universal, especially '/ n'. We are often used as a branch. However, different systems use different branch characters, so these characters have violated Java platform independence in certain sense. Error example: system.out.println ("Hello / N" Name; we can replace other methods, such as Println (), which play the same role in different system platforms. The latter recommends everyone to use this method: System.GetProperty ("line.separator") Reference: David Flanagan: "Java in a nutshell". O'Reilly, November 1999: Third Edition, PP. 191-192 (10) The internal class "private". Java allows a class to include another class, with a Java Byte code without this concept. The class is interpreted as a Package-Private class. From a deeper extent, any internal private object containing classes can be accessed by internal class accessible to other class access within the same package. Error example: public class inner {class inner_class {void setvalue (int i) {_value = i; // Now package can be accessed}} private int _view;} So you need to add private class inner_class reference: staticly scanning java code: Finding security Vulnerabilities. John Viega, Gary McGraw, Tom Mutdosch, And Edward W. Felten IEEE Software September / October 2000 (11) Do not make interface sequence If a byte array contains a serialized object. An attacker can read the internal status of this object (including Private). Error example: public interface sample extends java.io.serializablejava rules development articles

Author: flyingwcy Views: 165 Time: 2004-3-13 Reprinted from: Description JAVA Java Research Organization rules described in this article is divided into three main levels herein, this abandoned rarely encountered in the case of normal development, and those with There is a less advanced article in the future. There are six useful international software development important attention to string issues, complying with these rules can improve the efficiency of the program, making the code more readable. (1) If the JDBC connection is not turned off, you need to turn off in the "Finally" method if the database connection fails or does not release the connection, it seems irrelevant. However, other users need to wait for a longer time, so that the database utilization efficiency will fall. Make sure your code is released in any case, including errors or procedures to terminate. Turn off 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 {ix!} Null &&! Con.isclosed ()) {con.close ();}} (2) Try to avoid use of "thread.Resume (),'Thread.Stop () ','Thread.Suspend () and'Runtime .runfinalizersoneXit () 'method. These methods are also useful in usual development or in textbooks, but these methods will lead to the tendency of four locks. There is sufficient information to explain why it is not recommended to use the above method. 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) In order to use L instead of L. Because L is easy to mix together. 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) The best in JSP Note Write a note on the JSP file header, which can help others understand your code. This rule applies not only to JSP, but also the documentation for any development. Correct example: <% - JSP Comment -%> (5) A clear initialization of all fields inside a constructor because there is no initialization field being a potential bug, so it is best to initialize all fields in the class.

Especially static fields, it is best to allocate an initial value error in the beginning, an 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; INT i = 5; Private Int J; Private Int K;} Reference: http://www.ambysoft.com/javacodingstandards.pdf (5) International Development Suggestions: Logic Operators Do not have a single character in front or back Do not use logical operators before and after, if code is to run in a country environment. We can use characters compare methods that use unified characters to compare criteria to define properties of characters. 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_sletter;}} reference: http://java.sun.com /DOCS/books/tutorial/i18n/intro/checklist.html More characters Compare methods Please refer: http://java.sun.com/docs/books/tutorial/i18n/text/charintro.html (6) International Development Suggestions: Do not use'Date.toString () 'not using'DATE.TOSTRING ()' method, date format for regional and language different countries, not to use. Error example: The'DateFormat' class provides a predefined format type to specify a 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 Suggestions: Don't For digital variables in the development of a 'Tostring ()' method, do not use the 'Tostring ()' method for digital variables, for any subclasses of java.lang.Number. In this case, Java is also formatted with the "NumberFormat" method in this case: BigDecimal, Biginteger, Byte, Double, Float, Integer, LONG, AND SHORT. Examples of errors: public class NTS {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 recommendations: Do not use the'String.Equals () method Never use the'String.Equals () method, because it is not necessarily compared in the unified character comparison criteria. The predefined sorting rules provided by'collator' are sorted, and the Collator class calls the'getInstance () method. In general, you can create a collator for the default local.

转载请注明原文地址:https://www.9cbs.com/read-76030.html

New Post(0)