Code Statute

xiaoxiao2021-04-08  4

J2EE is a major project, and large projects often need teamwork, and consistent programming style is the guarantee of teamwork.

First, starting from the Start from the Standard

Sun's Java Coding Convertions

Coding regulation points:

1) give a difference, meaningful name gives parameters. For example, the parameters in the assignment method of an attribute can be named: NewProperty.

2) If you use a member variable, you must use it.

THIS.

3) The member variable name is as detailed, while the local variable name is as short as possible. For example, the same example is SYSTemuserInfo instance, the member variable should be named: SystemUserInfo. The local variable should be named: Newuser.

Code organizational regulation points:

1), through functional tissue methods, not through access.

2) divide the code into different areas. For example, the method of implementing an interface can be used

/ / -------------------------------------------------------------------------------------------- ---------------------

//Mplementation of Interface MyInterface

/ / -------------------------------------------------------------------------------------------- ---------------------.

3) Any static variable, static method, especially the main () method should not exist. UT test should be done by JUnit.

4) put all the members variables together.

5), must have a constructor.

6) Publish the public method by class, not through the implementation of the interface (

? ? ).

7) The Abstract method should be protected.

8), the protected method is indeed useful for subclasses.

9) If the implementation method does not have an association with any previously implemented code.

Second, Responsibilities (Allocation of Responsibilities)

Every class should have a clear duty. Inappropriate code should be reconstructed, usually in the Helper class, the Inner Class is sometimes a good place. A Helper class's inheritance system is usually better.

Even if JavaDoc and comments are included, a class should not exceed 500 rows.

Similarly, the method is also the same. Each method should have a clear responsibility, and all operations should be on the same abstraction level. The length of the method should be displayed in one screen. Does not include javadoc should be around 30-40 lines.

Third, avoid code repeat (Avoid Code Duplication)

Duplicate code often leads to many problems:

1), too many code.

2), it is not easy to understand.

3), inconsistent implementation.

4), the same thing needs to modify multiple places.

Fourth, avoid character constants (Avoid Literal Constants)

In addition to being known: 0, NULL, "" Think, other character constants should not be used in the Java class.

IF (Balance> 10000) {throw new spendinglimitexceededException (balance, 10000);}

Character constants often lead to:

1), the code cannot be self-description. For example, 1000 in the code, you don't know if he is the length, or the size.

2), it is not easy to understand. 3), the same thing needs to modify multiple places.

V. Visibility and Scoping

Members variables and methods should have the smallest visibility. Local variables should be declared in the true code block.

1. Public member variables (public instance variables)

Public member variables often fail design or lazy programmakers.

2, protected, member variables in the package (protected and package protected instance variables)

It is forbidden to use Packag visibility. Do not use protected visibility unless it is constant.

Multi-member variables should be private.

3, visibility

Should be as small as possible.

4, range of variables

The declaration of variables should be as close as possible, where variables are used.

5, internal class and interface (Inner Classes and Interfaces)

Internal classes and interfaces help Java avoid naming domain pollution. Internal classes are often used to help primary and class implementation.

Static internal and non-static internal classes: Static internal classes can be accessed by the instance of the primary class. The inside of non-statics cannot be.

Anonymous Inner Classes cannot promote the reuse of the code, no constructor, can only be accessed by one way. So don't advocate it.

Public void anonclass () {

JDBCTemplate Template = New JDBCTEMPLATE (NULL);

template.update (new PreparedStatementCreator () {public PreparedStatement createPreparedStatement (Connection conn) throws SQLException {PreparedStatement ps = conn.prepareStatement ( "DELETE FROM TAB WHERE ID =?"); ps.setInt (1, 1); return ps;} });

}

Public void methodclass () {

JDBCTemplate Template = New JDBCTEMPLATE (Datasource);

Class Counter Implements RowCallbackHandler {Private INT Count = 0; Public Void ProcessRow (ResultSet RS) THROWS SQLEXCEPTION {Count ;} public int getCount () {return count;}}

Counter counter = new counter ();

Template.Query ("Select ID from MyTable", Counter;

INT count = counter.getcount ();

}

6. Using Final Key 1, Method Overload and Final Method

It is usually considered to set a method to Final might reduce a reusability of a class because it can't extend this method. However, actually use overload to expand a class.

It is not worthy.

It is recommended to set all the non-virtual methods of all public and protected to Final. This can exclude bugs that should be caused by subclass of errors. Overload means potential dangers. "Opening" indicates that an object should be open, and the modification is closed. Although the "new code is added to a program to add new functions to a program by overloading a specific class, add new features to a program without modifying the previous code." However, there is a better way to extend an object, not by overloading methods, such as Strategy Design Pattern.

For the way of modification, it is recommended to call a specially added imaginary method in the end of the method to achieve future expansion. This can be extended, and there is no functionality that has changed the method because of the wrong extension.

Public final void init () {// init help // ... oninit ();} protected abstract void oninit (); If you overload a method, you need to completely subvert the original code of this method, you can only The instructions of the inheritance system have problems.

2, Final class

If you do not need to modify the class, you can consider setting it to Final.

3, Final member variable

A Final variable can only be initialized in the latter constructor when declaring. The Final variable is also the only way to achieve constant in Java. Usually the final variable can also expose the class's own variables and avoid modification.

7. Realistic TSTRING () methods to facilitate diagnostics and logs in the toString () method to implement the status of the object is a good practice, and there is a lot of help to log.

Eight, defensive programming skills 1, proper NULLS processing

It is very important to define an object when NULL is important. It is recommended to follow the following suggestions:

1), record the behavior when accepting NULL is accepted. It is usually recommended to check if the parameters are null, and the method is recorded in the Null parameter and when you throw NullPointRexcetion.

2) Write the test case to test the behavior when using a NULL call method, whether or not the description.

3) Don't assume that a method will never be NULL.

2. Considering the order of comparison

Although the following two lines of code are normal, if the MyStringVariable is NULL, the above sentence will be wrong, and the second sentence will return false.

IF (My_String_Constant)) IF (My_String_Constant.equals (MyStringVariable)) 3, use short-circuit evataration

We can use Java's short-circuit assignment, such as

IF ((o! = null) && (O.GetValue () <0))

Even if o is NULL, there will be no problem. When o is NULL, the second will not be executed. 4. Distinguish error message and message content message "error in com.foo.bar.magicservlet: cannot load class 'com.foo.bar.magic'" ratio "error in com.foo.bar.magicServlet: Cannot loading Class COM .foo.bar.magic "describes the wrong information more detailed. 5. Using Arrays instead of Collections Java using Collections means that type conversion must be performed, and the type conversion code is often slow, complicated, easy to problem, so you should use the type of Array as much as possible. Nine, the document in any language is unforgivable in any language. Java provides conditions by JavaDoc for standardized documents. Documentation purpose:

1) Provide a contract for objects and methods. Test Case is also a good description. And documents and test cases should remain synchronized.

2) Avoid developers must read it before using the code. There is no need to verify how the code works or does it work. Javadoc determines what, test the CASE determine the code written in the document.

3) Explain non-obvious implementation.

Recommended document specification:

1) Learn how to use Javadoc (such as @ param, @ throws). You can view the corresponding version JDK Javadoc.

2) Write Javadoc for all methods, including private methods. You can use the tool to generate a framework, then fill in other information yourself, pay special attention to how to handle NULL.

3), always record the method of running time (Runtime Exceptions). Can be declared by @throws.

4), Javadoc statement and method

What did you do. Can be used inside using // or / *

How to do it.

5), use / * Note to more than 3 lines, use // note less.

6) write a comment for all member variables.

7) No need to write a notes for a specific implementation of the interface. Use the @see tab to point to Javajoc of the interface.

8) Always annotate the type of key and value of the MAP type.

9), also comment on the type of Collection.

10), add a comment only for the required code. Until the code is not a good explanation, add a comment for them.

11) Do not add a comment for an obvious code.

12) Use any opportunity to improve the document.

13), contain a package.html in each package.

14),

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

New Post(0)