Peking University Jade Bird Java Programming Specification

xiaoxiao2021-03-06  51

Java programming specification

Application range

This specification is applied to projects in J2EE specifications (including JSP, Servlet, JavaBean, EJB) in all projects, should comply with this specification. At the same time, it can also be used as a reference for other items.

2. Design classes and methods

2.1 Creating a class with strong internal strength

The importance of the method is often more likely to understand the importance of the class, and the method refers to a piece of code that executes a unified function. Types of common errors are a container that is only used to store methods. Some developers even played this idea and put all their methods into a single class.

The reason why the reason why the correct understanding of the class is that the implementation of the class does not actually affect the execution of the program. This doesn't matter if all methods are placed in a single class or in dozens of classes. Although the number of classes has little effect on the execution of the code, the number of classes sometimes has a large impact when creating a code that is easily debugged and maintained.

Category should be used to organize related methods together.

When the class contains a set of closely associated methods, the class can be said to have powerful cohesive. This class has weaker cohesiveness when the class contains many mutually disconnected methods. It should be strive to create a class of internal gathering.

Most of the projects contain many methods that are not very suitable for combining other methods. In this case, a comprehensive housing class can be created for these unqualified methods.

When you create a class, you should know what the meaning of "modular" this term is. The basic purpose of the class is to create a considerable independent program unit.

2.2 Creating a loose connection and highly dedicated method

1. Make all methods to implement specialized tasks

Each method should perform a specific task that should exceon completion of this task. You should avoid creating a method of performing many different tasks.

There are many benefits to creating a dedicated method. First debug will become easier.

2. Try to make the method become independent methods of self-contained

When a method relies on the call to other methods, it is called a method closely connected to other methods. Tightly connected methods will make debugging and modifications become more difficult because it involves more factors. A loose connection method is superior to a closely connected method, but you can't make each method a separate method.

To enable the method, one of the methods is to minimize class variables.

When you create a method, try to treat each method as a blackbox, and other routines should not be able to understand the internal work of the method, which should not be understood by understanding the project. This is why your method should rely on parameters and should not rely on global variables.

When you create a dedicated method, consider the following guidelines:

1) Place complex processes in a dedicated method. If the application uses a complex mathematical formula, consider putting each formula into its own method. Other methods such as using these formula do not include actual code for the formula. This can also be easier to find problems related to formulas.

2) Put the data input / output (I / O) into a dedicated method.

3) Isolate the code that may be modified in the dedicated method. If you know that a process is often changed, put this variable code into a dedicated method so that you can make more easier to modify and reduce the possibility of unintentional issues.

4) Package the business rules in a dedicated method. Business rules often belong to the code category to be modified, should be separated from the rest of the application. Other methods should not know that business rules, only use these rules only to be called.

3. When designing classes and methods, to achieve the following purposes:

1) Creating a method of easier debugging and maintenance

2) Create a class with powerful internal strength

3) Creating a highly dedicated method

4) Creating a loose connection method

5) Try to make the method independence

6) Improvement of fans

7) Reduce the fan out of method

2.3 Programming Principles

1. Method and class give a good name

In order to make the code easier to understand, one of the easiest ways is to give your method a strong name. Function name DoIT, Getit readability is difficult to compare with CalculateSaStax, RetrieveUserid. The code consisting of abbreviation method is difficult to understand and maintain, and there is no reason to do so.

Give the correct naming, make the program engineering debugging and maintenance work greatly changed. Please carefully treat the method named, do not reduce the understandability of the method in order to reduce the type of operation.

Actual application example:

1) When naming the method, you should write the letter mixed. If the sentence uses uppercase letters, then read it is very difficult, and the sentences whitwriting letters use the sentence, it is easy to read.

2) Do not use abbreviations when defining method names. If you think some of the projects in your application should use abbreviations, please contact these situations and make sure everyone uses these abbreviations in all hours. Never abbreviations some words in some methods, but do not use abbreviations in other methods.

2. Give a single exit point for each method

3. When you create a method, it is always explicitly defined.

1) If you really want to create a public method, please explain this to the code reader.

2) The amount of work that the code reading reader needs to be put into progress by imparting a clearly defined scope to each method. You should make sure you give the method to give the most meaningful scope. If a method is only called another method in the same class, then create it into a private method. If the method is called from multiple methods in multiple classes, this description is a common method.

4. Pass the data between the method

Use class variables should be avoided. In general, the smaller the scope of the variable, the better. In order to reduce class variables, the method is to transfer data as a parameter between different methods, rather than letting the method share class variables.

1) Specify the data type for each parameter.

2) Always have to test, never assume that you have no problem. One error that programmers frequently assume that data is not problematic when writing methods. In the initial programming phase, such assumptions are not subject to when writing callout methods. At this point you can know what is the license value of the parameters and provides these values ​​as required. But if you don't test the data of the parameters, then the following cases will bring you a big trouble: Another person creates a call method, but this person does not know the allowable value; you added a new one later The method of calling the method, and the bad data is passed.

3. Naming agreement

The definition of all variables should follow the Hungarian nomenclature, which uses a 3-character prefix to represent data types, 3 characters must be lowercase, and the prefix is ​​a name that consists of a single word or multiple words, and each word The first write letters uppercase, other letters lowercase, so that the correct selection of the variable name can be made.

In this way, in a variable name, it can reflect both the meaning of the variable type and the value stored in the variable, which makes the code statement readability and more easily understand.

3.1 package, class and method naming

Marking type

Naming agreement

example

package

l All lowercase.

l The identifier is separated by a dot number. In order to make the name of the package easier to read, Sun is recommended to separate the identifier in the package.

l Sun's standard Java distribution package is started with identifier .java.

l The name of the global package begins with your institution's Internet.

Partial package:

Interface.screens

Overall package:

com.rational.www. interface.screens, INTERFACE.SCREENS

Class, interface

The name of the L class should use noun.

l Each word should be capitalized.

l Avoid using a word abbreviation unless its abbreviation is widely known, such as http.

Class Hello;

Class HelloWorld;

Interface apple;

method

l The first word is generally a verb.

l The first letter is small, but the first letter of the intermediate word is uppercase.

l If the method returns a value of a member variable, the method name is typically a get member variable name. If the returned value is the BOOL variable, it is generally used as a prefix.

l If the method changes the value of a member variable, the method name is generally: set member variable name.

GetName ();

SetName ();

isfirst ();

variable

l The first letter lowercase, the first letter of the intermediate word.

l Do not use _ or & as the first letter.

l Try to use short and meaningful words.

l Single characters' variable names are generally only used for very short variables. I, J, K, M, N are generally used for Integers; C, D, and E are commonly used for Characters.

l If the variable is a collection, the variable name is applied.

l Named components use Hungarian nomenclas, all prefixes should follow the same component name abbreviation list.

String myname;

Int [] student;

INT I;

Int n;

Char C;

Btnew;

(BT is the abbreviation of Button)

constant

l All constant names are all uppercase, and the words are separated from '_'.

Int max_num;

3.2 Others

If the developer encounters the type unrecovered in the above table, please inform the relevant administrators in writing, and the list of the list of management is not allowed to enable unspecified new variable prefix.

4. Use constants

4.1 Use constants

1. The constant is easy to make an error in data input

One of the main issues of constants is that you can easily make mistakes when you type numbers, thereby reversing the number of numbers. For example, when you type a number 10876, it is easy to type 10867 or 18076. Unlike the method of processing variables and reserved words, the compiler does not intervenes the position and incorrect numbers, and sometimes a simple error will not be immediately expressed, and when the problem is expressed, they will calculate the random computing error. The form of appears, these errors are difficult to accurately position. When replacing constants with constants, the compiler will check the validity of constants when compiling. If the constant does not exist, the compiler notifies you and refuses to compile, which can eliminate the problem brought by the number of incorrectly, as long as the constant has the correct value, all code to use this constant also use the correct value. .

2. The constant is difficult to update

3. Constant makes your code easier to read

After using constants, an additional advantage is to make the created code easier to read. The constant is very intuitive. Maybe you know very well on the constant, but others don't understand. By naming the usual given, the code to use these constants is more intuitive, easier to read.

A wide range of scope is given to constants, which is different from the case of using variables. In an application, you will never create the same constant twice. If you find that you copied a constant, you will turn the original constant to a wide scope until the constant is available for reference to all methods.

5. Variable

5.1 Define variables with focus

Variables for multiple purposes are called unfocus (multi-focus) variables. The meaning of the non-focus variable is related to the execution process of the program. When the program is in different locations, the meaning it is not fixed, so that it has brought trouble to the program readability and maintainability.

5.2 Abbreviations only for common variable names and long variables

If you need to abbreviate the variable name, you must pay attention to the consistency of the abbreviation rules across the code. For example, if you use a CNT in some areas of the code, in other regions use COUNT, it will add unnecessary complexity to the code.

There should be no abbreviations in the variable name.

5.3 use unified quantifiers

By placing a quantifier at the end, you can create a more unified variable, which is more likely to understand, and it is easier to search. For example, use StrCustomerfirst and StrCustomerlast instead of StrfirstCustomer and StrlastCustomer. Quantifier list:

Quantifier suffix

Description

First

The first set of variables

Last

The last set of variables

NEXT

Next variable in a set of variables

Prev

One of the previous set of variables

CUR

Current variables in a set of variables

5.4 Boolean variables using affirmation

When named the Boolean variable, it is always necessary to use the positive form of variables to reduce the difficulty of other developers in understanding the meaning representing the Boolean variable.

5.5 Select the best data type for each variable

This will reduce the demand for memory, speed up the execution speed of the code, and reduce the possibility of error. The data type for variables may affect the result of the variable for calculation. In this case, the compiler does not generate a running period error, which only force the value to meet the requirements of the data type. This type of problem is very difficult to find.

5.6 Unscarked the scope of the variable

If the scope of the variable is greater than the range therewith, the variable can continue to exist and still occupy resources for a long time after the variable is no longer required.

Their main problem is that any of any classes can be modified, and it is difficult to track where to modify it.

Occupy resources are an important issue involved in the scope. For variables, try to narrow the scope will have a huge impact on the reliability of the application.

6. Format of code

6.1 When formatting the code, the purpose to achieve

1. By the code segmentation of the code and the code segment that is easy to understand, make the code easier to read and understand;

2. Use the space lines and annotation lines to separate the code blocks logically in the program. For example: variable declaration part and code statement separation; in a longer method, complete the separation between code blocks between different functions. To avoid logically confusing separation, such as a logical function code block is separated by a space line, but there is no separation between adjacent function code blocks, which will cause an illusion to the program reader.

3. Reduce the work that needs to be done to understand the code structure;

4. Make the reader of the code without the assumption;

5. Make the code structure as much as possible.

6.2 Programming Principles

1. To put multiple statements on the same line

Whether it is a variable statement, or the statement is not written in a line.

2. Removal

When you set the variable to a value, all subsequent line indentation locations should be the same as the variable value of the first row;

When you call a method, subsequent row into the beginning of the first parameter;

When you set the variable or property to or equal to the calculation result of the expression, split this statement from the back to ensure that the expression is as far as possible.

3. Indoosure after the IF statement;

Indenge in the ELSE statement

Indigidation after the Switch statement

After indentation after the CASE statement

Indenge in the DO sentence

Each row of statements that have been divided by row

Index to the code that belongs to the row.

4. Insert an empty line between each statement group that performs a unified task. A good code should be composed of a process or related statement group arranged in a logical order.

7. Comment of the code

7.1 Purpose of using code annotations

1. The role of text description code (ie why you want to write this code, not how to write);

2. Indicate the writing ideas and logical methods of the code;

3. People noticed the important turning points in the code;

4. Make the code readers do not have to simulate the implementation of the code in their minds.

7.2 Programming Principles

1. Use the text to explain the role of code:

What is the simple duplication code to write, such a note does not add any information to the comment. If you use a good naming method to create a straight-up code, then these types of comments absolutely increase what information. 2. If you want to violate it Programming principle, please explain why

Sometimes you may need to violate a good programming principle, or use some informal methods. When you encounter this situation, please use internal annotations to explain what you are doing and why do you want to do this.

A very high skillful code segment must be added detailed notes, do not let other developers spend a long time to study a high-tech but not understandable block.

3. When using the comment, when is wrong, when it is wrong and why error

4. Notes before writing the code

One of the methods to add comments to the code is to write a comment before writing a method. If you like, you can write a comment or pseudo code for the full sentence. Once you use the comment, you can write it online. Code.

5. Write a comment before the code to be commented

Note must appear before you want to comment, don't write a comment for this program after a certain program, first see that the annotation of the program will have a certain help.

If possible, add an empty line with the above code in the comment line.

6. Solid color character notes only for main comments

When you are separated in your comment, use a line of air injection rows to complete, don't use the solid color character to keep the layout clean and clear.

7. Avoid forming a comment box

The annotation box that is surrounded by the star, the asterisk on the right looks very good, but do they add any information to the comment? In fact, this will add a lot of work to people who write or edit the comments.

8. Enhance the readability of the annotation

The comment is for people to read, not allowing computer to read.

1) Use a complete statement. Although not necessarily divided into paragraphs (preferably not to be divided into paragraphs), you should try to write annotations into a complete sentence.

2) Avoid using abbreviations. Abbreviations often make annotations more difficult to read, people often use different methods to abbreviate the same words, which will cause many confuses, and if they must be abbreviated, they must be unified.

3) Override the entire word to highlight their importance. To make people pay attention to one or more words in the comment, please use your uppercase letters.

9. Index to the annotation to align it with the following statements.

Note It is usually located in front of the code they want to explain. In order to visually highlight the relationship between its code, then indent the annotation, so that the code is in the same level.

10. Give an annotation header for each method

Each method should have an annotation header. The annotation header of the method can contain multiple text items, such as input parameters, return value, original author, finally editing the programmer, last modified date, copyright information.

11. When the tail injection is used in this code segment structure, they make the code more difficult to read.

When using multiple row tailings (such as multiple variables for the top of the method), they should be aligned with each other. This allows them to read some.

12. When will you write a comment?

1) Please add a comment in front of each IF statement.

2) Add a comment in front of each Switch statement. Like the IF statement, the Switch statement is used to evaluate an expression that affects the execution of the program.

3) Add a comment in front of each cycle. Each loop has its role, in many cases this effect is unclear.

7.3 Notes those parts

project

What are your comments?

Arguments/

parameter

Parameter Type

What is the parameter to do?

Any constraint or prerequisites

Example

Field /

Field / property

Field description

Note All non-variables used

Example

Parallel event

Visibility decision

class

Purpose

Known problem

Class development / maintenance history

Note invariant

Parallel strategy

Compilation unit

Interfaces defined in each class / class contain a simple description

File name and / or identification information

Copyright Information

interface

purpose

How should it be used and how not used

Local variable

Use / purpose

Member function comment

What is the function function and why do it do this?

What parameters must be passed to a member function member function to return anything?

Known problem

Any abnormality thrown by a member function

Visibility decision

How does a member function change object?

Contains history of any modification code

How to call an example of the example of the member function to apply for prerequisites and post criteria

Member function internal annotation

Control structure

What did the code have done and why do this?

Local variable

Difficult or complex code

Processing order

7.4 Example

7.4.1 Caption:

Mainly used to describe files, classes, methods, algorithms, etc. Generally used in front of documents and methods, it can also be placed anywhere in the document. At the beginning of '/ *', '* /' ends. example:

......

/ *

* Note

* /

......

7.4.2 Row Note:

Mainly used inside, the code, variables, flows, etc. will be described. Similar to the block annotation format, but the entire annotation occupies a line. example:

......

/ * Note * /

......

7.4.3 Due Notes:

Similar to the row opinions, put on the code's peers, but there is enough space between the code to make it easy. example:

INT m = 4; / * Note * /

If there is a plurality of ends in a block, the indentation of each annotation should be consistent.

7.4.4 Ring Note:

Similar to the row opinions, placed in the end of each row, or occupies a line. To ... beginning.

7.4.5 Document Note:

Similar to block comments, but can be processed by Javadoc to generate an HTML file. At the beginning of '/ **', '* /' ends. Document comments cannot be placed in a method or block. example:

/ **

Comment

* /

8. Expression and statement

8.1 Each line should have only one statement.

8.2 If-else, if-elseif statement, in any case, there should be "{", "}", the format is as follows:

IF (Condition) {

STATEMENTS;

} else if (condition) {

STATEMENTS;

} else {

STATEMENTS;

}

8.3 The FOR statement format is as follows:

For (inTIALIZATION; UPDATE) {

STATEMENTS;

}

If the statement is empty:

For (Initialization; Update);

8.4 The WHILE statement format is as follows:

While (condition) {

STATEMENTS;

}

If the statement is empty:

WHILE (CONDition);

8.5 Do-While statement format is as follows:

Do {

STATEMENTS;

WHILE (condition);

8.6 Switch statement, each Switch should contain the default sub-statement, the format is as follows:

Switch (condition) {

Case ABC:

STATEMENTS;

/ * Falls through * /

Case Def:

STATEMENTS;

Break;

Case XYZ:

STATEMENTS;

Break;

DEFAULT:

STATEMENTS;

Break;

}

8.7 TRY-CATCH statement format is as follows:

Try {

STATEMENTS;

} catch (exceptionclass e) {

STATEMENTS;

} finally {

STATEMENTS;

}

9. Error handling and exception event

The usual idea is to use exception handling on errors: logic and programming errors, setting errors, destroyed data, resource depletion, and so on. The usual rule is that the system should not produce any abnormalities in the normal state and without heavy load and hardware failure. Appropriate log mechanisms can be used to report an exception, including abnormal occurrence. Do not use an exception implementation to control the program process structure.

10. Package, affairs

1. Non-business public components separate package

2. Each business process is individually packaged

3. Calling of a method (component) should be able to complete a function or process, that is, integrity

4. Calling of a method (component) complies with ACID transactionality

5. The call to multiple methods (components) should be included in a transaction

11. Portability

1. Try not to use classes or methods that have been labeled as not approved.

2. If you need to wrap, try to use PrintLn to replace "/ n" in a string.

3. Use the separator () method instead of "/" or "/" in the path.

4. Use the Pathseptarator () method instead of ":" or ";".

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

New Post(0)