Java rules

zhaozj2021-02-12  149

Java Rules Basic Articles FlyingWcy Original This article is divided into 5 levels, and the level 1 is the most basic and most important level, and other rules will be written in the future. 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 (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/codeconv/html/codeconventions.doc6.html# 431 (5) often call Superize () 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 ()); // FIXEDt71 = null;} private T7 t71 = New T7 ();} Reference: Nigel Warren, Philip Bishop: "Java in Practice - Design Styles and IDiomsfor Effective Java". Addison-Wesley, 1999. PP.110-111 (8) Do not use un recommended API to try 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' for all serialized classes to 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

Rules developed piece of JAVA: JAVA Description flyingwcy 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 less than a high-level articles which appeared later. 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 using '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 documentation2.http: //java.sun.com/j2se/1.3/docs/guide/misc/threadPrimitiveDeprecation.html3.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 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) 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;}}: 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.htmlhttp: //java.sun.com/docs/books/tutorial/i18n/dormat/dateformat.html (7) Internationalization Development Suggestions: Don't Digital variables use 'toString ()' Method in global development, 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.htmlhttp: //java.sun.com/docs/books/tutorial/i18n/format/numberformat.html (8 ) International development suggestions: Do not use 'string.equals ()' method Never use the 'string.equals () method, because it is not necessarily compared in the unified character comparison criteria. The predefined finishing rules provided by 'collator' are sorted, and the Collator class call 'getInstance ()' method, in general, you can create a collator for the default local.

For example: collator mycollator = collator.getinstance (); When you create a collator, you can also specify a special Locale. For example: collator myfrenchcollator = collator.getInstance (locale.french); then call 'collator.compare ()' to perform a local character comparison MyCollator.comPare (S1, S2); From here you can learn more about Collator Information: 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.htmlhttp: //java.sun.com/docs/books/tutorial /i18n/text/locale.html (9) International Development Suggestions: Do not use '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 Suggestions: Do not use 'Time.toString () method because the time format is different in various countries. If you use the date format class, your application can display the correct display time and date in the world. First, create a formatter with 'gettimeInstance ()' method. Then, call the 'Format ()' method. Error example: public class tts {public void printtime (Time T1) {string TimeStr = T1.toString (); system.out.println (TIMESTR);}}}}}}}}}}}}}}}}}}}}}}}}}}}}}} 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 (timesp);}}

Java rules Intermediate FlyingWcy Original This article describes the Java rules in this article divided into three main levels. The intermediate is a relatively large level of usual development, and other rules will be written 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.byteArrayInputStream If the method is returned, there is no calling 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 if if if if if there is an else nested, {} is an essential error example: IF (i <5) IF (i <2) i ; else -; After modification: 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 this is done 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 ) {// fixedsystem.out.println (i);} (5) Do not define the method into main (). In Java, the main () method is a special Methods. So don't define such names when you define methods, so as not to cause sink. (6) Do not directly or indirectly define 'java.lang.Error' of 'Java.lang.Error' to override this method when JVM occurs, if you define a direct or inactive class inherited the class 'Error', that is, 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 the superiometrics of 'java.lang.exception' and 'java.lang.Error', 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.

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

New Post(0)