Java Development Specification Summary _ Code Coding specification

Source: Internet
Author: User
Tags modifiers

The norm needs to be noticed in the regular coding process, which is a good habit to develop slowly.

1. Basic Principles

Mandatory principle:
1. The StringBuilder of the string must be used;
The use of 2.try...catch

Try {}catch{Exception e    e.printstacktrace ();} finally {}// can be used in the outermost action, all other places are forbidden to use;
Try {    // program code }catch(Exception e) {    // is empty, nothing is written } // prohibit use in any scenario
Try {}catch{Exception e    thrownew runtimeexception (e); // Optimal first-use notation } finally {}

     1. For situations in which you do not know what to do or how to handle after capturing, do not catch exceptions, leave the egress layer to capture processing;
     2. Return type is collection, In a method declaration, you must use generics, and you must indicate in Javadoc what conditions return null, and in which case an empty collection is returned.
     3. For methods, variable declaration scopes have the following precedence: private, protected, public, the following precedence is used for variables: Local variables, instance variables, class variables, If you must take an instance variable or class variable, to ensure thread safety, if possible to use Threadlocal to save instance variables or class variables;
     4. If it is not necessary, do not define the variable or the new object in the loop. Try to get to the new object at the last minute you need it;
     5. If it is not necessary, do not use Try...catch in the loop;
     6. Comments in the form of a line comment for more complex logic in the Java code, in which the block annotations (/**/) are not allowed,
     7. The name of the Java class The first child must be capitalized, with more than one word, and the first letter of each word capitalized
     8.jsp must have all lowercase names,
     9. Spring's bean configuration file name must be lowercase, formatted as <bean id= "" In the Xxx.bean.xml,xxx.bean.xml profile, where the ID is to place the first letter of the class name in lowercase. The profile name of
    10.xwork must be lowercase and written in xwork_xxx.xml format, where xxx is the abbreviation of the business name;
   11. log processing,

if (log.isdebugenabled ()) ex.printstacktrace (); Else log.error ("Delete from database: [" + Entity.getclass (). GetName () + "] Instance failed", DAEX); Throw New Persistenceexception ("Delete from database: [" + Entity.getclass (). GetName () + "] instance failed", DAEX);

12. System.out.println () is forbidden in the code to debug the output, if you want to use debug information, you must use Log.debug (). Use Log.info () for the necessary information to output;
13. Do not appear useless import in the class, can use the IDE tool to optimize, the class submits the code before the format;
14. Classes with business logic must write JUnit unit test classes;
15. Internationalization support: The FTL template is not allowed to appear in Chinese characters, to be put in the corresponding properties file, the properties file is placed in the same directory as the action class; FTL's code is all in UTF-8 format. ; properties file name: Chinese: Action name + "_zh" + "_CN". Properties, English: Action name + "_en" + "_us". Properties
16. A program file should not be more than 2000 lines
17. Reduce the scope of the object as much as possible, so that the visible range and the lifetime of the object will be as small as possible, do all the possible priority to use local variables, there is no way to use global variables, priority to use threadlocal to deal with.
18. One method accomplishes a single function, with different functions encapsulated into different methods.
19. Handle exceptions or conversions as much as possible, and do not blindly package exceptions
20. If the object must be cleaned up within a certain range (rather than being recycled as garbage), use a try block with a finally clause to clean it in the finally clause.
21. For the organization of some logically related classes, consider placing the definition of one class in the definition of another class, which recommends using internal classes (such as event responses in the interface layer). The inner class has access to all members of all the perimeter classes.
22. Access to member variables is best achieved through the Getter/setter method, which guarantees the legitimacy of access and code tuning
23. Prioritize interfaces rather than abstract classes or specific classes. If you know that something is going to be a base class, you should first design it as an interface, and modify it to a specific or abstract class only if you must put it in a method definition or member variable. Interfaces are only related to the actions the customer wants (protocol), whereas classes tend to focus on implementation details.
24. Use the containers provided by the Java Standard Library. Proficiency in their usage will greatly increase productivity. Prioritize ArrayList to handle sequential structures, select HashSet to handle collections, select HashMap to handle associative arrays, select LinkedList to process stacks and queues, optimize sequential access, and make it less expensive to insert and delete into the list. But random access is slower. When using the first three, you should convert them up to list, set, and map so that they can be implemented in other ways when necessary.
25. An array is the most efficient way to store and randomly access an object's reference sequence, but when an array object is created, the size of the array is fixed, and if a new array is created when the space is insufficient, the efficiency is greater than the ArrayList overhead. So you have to use the scene explicitly.
26. Try to use the "private" and "protected" keywords. Once you mark the library's features (including classes, methods, fields) as public, you will never be able to remove them. In this way, the resulting changes have the least impact on the derived class, and it is especially important to keep it private when dealing with multithreading issues, because only private fields are protected, without worrying about being destroyed by the use of synchronization control.
27. Prohibit background business code to use the following code

Try {    something ()}catch(Exception ex) {}new Exception ()

2. Class Authoring Specifications

The structure of the class, usually in the following order:
1. Constant declaration
2. Static variable declaration
3. Member Variable declaration
4. Constructor section
5. Finalize section
6. Member Method Section
7. static Method Section
8. This order is recommended and can be modified according to certain scale in actual development, the principle is that the procedure is easier to read. such as sorting methods by importance, or alphabetically or by the relationship between methods.
9. Each method, including construction and finalize, is a segment. Multiple variable declarations are logically combined to form a segment separated by a blank line between the segment and the segment.
10. When declaring a class, it is necessary to indicate its access control, usually without modifiers, public, and private.
11. Between the method and the method, the large part needs to be separated by a blank line.
12. When writing generic classes, please follow the standard form. Includes defining Equals (), Hascode (), toString (), Clone (Implementing the Cloneable Interface), and implementing comparable and serialiable interfaces
13. For classes that do not need to be inherited during the design, try to use final

3. Specification of variable writing

1. For member variables, try to use private
2. One row for each variable declaration/definition (except for parametric variables), such as

int A; int b;

More than int A, b; Easier to read and easier to find bugs

3. Local variables must be initialized before they are used, and are typically initialized at the time of declaration.
4. The declaration of the variable to be placed at the beginning of the program block

Such as

 Public void MyMethod () {  int//  beginning of method block  if  ( Condition) {    int//  beginning of "if" Block    ...  }}

One exception is that in the for statement, the definition declaration is not only a row, but also within the expression, fully eclips generated, such as:

 for (int i = 0; i<100; i++)

5. The Declaration of the array adopts the < data type [] + variable name > method as

Char [] buffer;

Instead of

Char buffer[];

4. Method Writing Specification

1. For member methods, do not easily take member variables of public. The main modifiers are public, private, protected, none
2. Method declarations and function bodies can all be in one line in an empty method. For example: void Func () {}
3. Empty line between methods and methods
4. The document comment for the method is placed in front of the method, and cannot be blank line.
5. Avoid too many parameter lists, as much as possible to control within 5, if you need to pass multiple parameters, when the use of a host of these parameters to pass the object, to improve the readability and extensibility of the program
6. The method should not exceed 2 layers of the circulating cover
7. For classes that do not require subclasses to overload during design time, use the final
8. Try to avoid more than 100 lines of code per method (valid lines of code, not including comments), but must ensure the integrity of the logic
9. The method in the interface defaults to protected, exposing the method to public only if it is confirmed that the package of the other subsystem calls the method in its own subsystem's interface.

5. Language usage and writing code

1. Avoid the definition of a variable with the same name as a variable in the previous scope.
2. The method and method are separated by a blank line
3. Local variables are declared at the time of use, and local variables/static variables are initialized at the time of declaration.
4. In comparison with constants, the constant number is placed before the comparison expression as follows:

if ("Simplecase". Equals (obj)) ... if (null = = obj) ....

In 5.return statements, do not have complex operations.
6.switch statement, a default branch is required

Java Development Specification Summary _ Code Coding specification

Related Article

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.