Java code writing style and some simple precautions

Source: Internet
Author: User

From: http://www.cnblogs.com/panjun-Donet/articles/1144186.html

1. The style must be consistent (Consistent)
A compatriot asked me why the indentation format of our Java code had to be like this, not him. He liked his own style, therefore, the Code he writes is always in the style he is used. The results were killed in the code review and ordered to be modified. Therefore, he was greatly dissatisfied. It is a matter of style. In fact, there is no problem with his style, but in the project, it is different from the style of other programmers, and there is a problem. For example, this indentation, such as the variable naming method, different classes, and different methods, is difficult to understand. So once you choose a style, you must always implement it. If a style is defined in a project, even if it is not in line with your own habits, you must always implement it and never be unconventional.

2. indent)
Since it starts with indentation, we should first talk about the indent style. Generally, C languages such as Java adopt the indent style. There are four commonly used
A.k & R style
This is the earliest indent style of the C program, which was first used by C inventor Ritchie and his collaborators kernighan:
If (<cond> ){
<Body>
}
It is characteristic that braces and if are judged on the same line. Generally, it is indented into eight spaces or a tab key, but in C ++ and Java, it is also often indented into four spaces. Some people like to use two spaces. They think it is not good or obvious.

B. BSD style
Allman style, also known as Allman style, originated from Eric Allman, a Unix BSD programmer. He has written many programs for BSD:
If (<cond>)
{
<Body>
}
Features: braces and condition judgments are divided into two rows.

C. whitesmith Style
This style originates from whitesmith C:
If (<cond>)
{
<Body>
}

D. GNU Style
This style is only available in the GNU Emacs source program:
If (<cond>)
{
<Body>
}

So what is better to use in Java?Only A or B is recommended.. Sun has a Java code name Convention. We recommend.

3. tab or space (tabs vs space)
Or indent. How long should one indent be? Is it eight space bars or a tab key?

Java has a feature that is cross-platform. However, cross-platform means that its class can run on virtual machines on different platforms. Java source programs are sometimes not cross-platform. What? Can the source program not be cross-platform? Yes. Once a programmer sent some code and opened it in my environment, the program was ugly and messy. There was a place to indent it, without indentation, and some were indented, just like a strange stone, zookeeper is involved. This code quality is not good! Ask the programmer, and say that he is very beautiful. Does he still spend time beautifying them?

In the past, he did not pay attention to the style of indentation. In some cases, he used the tab key and spaces in some places. On some different platforms, the width of the tab key is different.

Speaking of this, I believe you are clear,When indent, try not to use tab, but use spaces.Fortunately, many editors can define the tab key on your keyboard as several spaces. Define it now!

How many spaces are used each time? Four. 2 is too small and not obvious, and 8 is too large to occupy space.

4. row width
8 space occupied by space keys, so I have 320 columns in a row. What is 8 spaces? Stop! Please remember that a row should not exceed 80 columns. Many terminals can only display 80 columns on one screen. If your statement is too long, find a way to break it and write it in several columns.

5. variable naming
Sun Java code convention defines naming rules for packages, classes, methods, and common variables in Java,

Naming rules for methods, variables, and constants

The naming rules for packages, classes, and interfaces have been described in the previous chapter. I will not go into details here. This section describes how to design Java programs, knowledge about naming rules for methods, variables, and constants.

1.10.1 naming rules for methods

The method is generally a verb. The first letter should be in lower case. When multiple words are mixed, the first letter of all words after the first word is in upper case, and the other letters are in lower case, for example, the following code:

Run ();

Runfast ();

Getbackground ();

In the declaration part of a method, it is usually necessary to provide a description of the function of the method, as well as descriptions of the return values and parameters of the method.For example, the following code:

/**

* How to display system information

* @ Param message system information Parameters

* @ Return message: system information is returned.

*/

Public String showmessage (string message ){

...

// Statements;

...

Return message;

}

If this method is no longer recommended for software product upgrades, you can add the keyword @ deprecated in the comments section of the method declaration.

1.10.2 variable naming rules

The naming rule for variables is that, except for variables, the first letter of the instance of all objects, the class and the constant of the class should be in lower case, when multiple words are mixed, the first letter of all words after the first word is capitalized, And the other letters are not in the lower case. The first letter of the variable, even if allowed by the system, should not be _ or $. Variable names should be compact and meaningful. The name of a variable should be easy to remember and understand. Even if the interval is long, the variable can be known by its name. In addition, the single-character variable names should be avoided unless temporary variables, for example, some integer single-character temporary variables: I, J, K, M, N, and single-character variables: C, d, E, and so on, as shown in the following code:

Int I;

Char C;

Float imagewidth;

1.10.3 constant naming rules

Constants in Java are generally named in uppercase letters and words, separated by underscores (_). This complies with the ANSI constant naming rules, as shown in the following code:

Static final int min_width = 14;

Static final int max_width = 1000;

Static final int get_the_memory = 128;

& Pay attention to the usage of static and final keywords. We will discuss them in detail in the following sections.

The code writing style and related formats and writing rules in the Java language are discussed above. The following is a simple Java program design practice to learn the learned knowledge.

1.11 Java programming practices

The Java programming style and format rules are explained in four aspects, which is the basis for writing master-level code.

1.11.1 rules for accessing instances and variables in Classes

Generally, do not declare the variables in the class as public unless the design requirements are the same. If the variables are not public, in this way, only public-type methods can be used to access related variables, such as the getxx () method. If the class you created does not have any behavior methods, you have to declare the variables in this class as public for external access.

1.11.2 rules for referencing static variables and methods in the class

When you try to reference static methods or static member variables of a class in your code, do not reference them through the instance objects of this class, though this is allowed. You should reference them through classes, as shown in the following code:

Public static classmethod ();

Myclass. classmethod (); // correct

Myobject. classmethod (); // incorrect (should be avoided)

1.11.3 variable assignment rules

Try to avoid assigning multiple values to a variable in a single row statement, which will make the code difficult and difficult to understand, such as the following code:

Username = user1.name = 'Jerry Lin'; // This value assignment method should be avoided as much as possible

Avoid assigning values to a single expression. For example, the following code is absolutely not allowed in Java:

If (I ++ = m ++ ){

...

}

Of course, you can change it to the following method to avoid syntax errors, but this is not recommended:

If (C ++ = D ++ )! = 0 ){

...

}

Avoid nested assignment whenever possible, which will waste a lot of time on the compiler, for example, the following code:

D = (A = B + C) + R;

The above assignment method should be changed to the following method:

A = B + C;

D = a + R;

1.11.4 comprehensive rules

1. Brackets

We recommend that you use parentheses () to define the sequence of expressions, so as to avoid non-subjective intent errors due to operator priority. Even if you know operator priority well and the code looks clear, however, other programmers may not be as clear as you are when reading this Code, for example, the following code:

If (I = J & M = N) // try to avoid

If (I = J) & (M = n) // correct

2. Return Value rules

Try to match the program structure with your intent, for example:

If (istrue ){

Return true;

} Else {

Return false;

}

The above program may feel "inactive" and should be changed:

Return istrue;

Similar,

If (condition ){

Return X;

}

Return y;

It should be changed:

Return (condition? X: Y );

3. Special Comment rules

You can use some special comments in the program to express your pseudo-code. For example, execute indicates that the Code has a problem but can be executed. fixme indicates that the Code has a problem and cannot be executed, for example, the following code:

If (istrue ){

// Execute

Int I = 0;

I ++;

} Else {

// Fixme because I is not declared

I ++;

}

So far, the Code style and format rules for Java programming have been fully explained. I hope you will try your best to apply them in your own code. It may be difficult to start the application, but as long as you stick to it, I believe that you will find the benefits of using a good code style for program design, and will gradually become an attachment to it.

Summary

This chapter describes in detail the Java programming style, including: Java file name and file organization structure, Java file comment header, package declaration and reference, Class) interface declaration, Java source file orchestration format, Java program annotation, variable declaration initialization and placement, Java program statement writing rules, space and blank line application rules, this chapter also provides three rules in Java programming practice (①
Rules for accessing instances and variables in the class; ② rules for referencing static variables and methods in the class; ③ variable assignment rules ). By learning the above knowledge, as long as you can stick to the above writing rules, you can only write the master Java code style in terms of the Code style, this is what you learned from this chapter. To keep approaching the core of the master-level Java code, continue to study the following chapters carefully.

Here are some precautions and common methods that sun does not mention.

A. Name variables with meaningful names
First, name your variables with the complete English words or conventions. For example:
Firstname
Zipcode
If the English language is not good enough, at least use the pinyin name that others can understand, such
Zhuzhi (address)
No one can understand the meaning of the variable if it is abbreviated or named randomly:
FN
ZC
Zz

B. constants should be named in uppercase and in offline format.
The constant in Java is static final:
Static final smth_bbs = "bbs.tsinghua.edu.cn ";

C. Name Collection variables in the plural.
Collection includes arrays and vectors. Use the plural number for naming:
MERs
Classmates
You can also use some modifiers to name them:
Somestudents
Alldepartments

D. Cyclic Variables
Generally, I, J, and K are used as cyclic variables.

E. Stream variable
Generally, in and out are used as stream variables, corresponding to inputstream and outputstream.
Class. If you are reading and writing iostream, you can use inout.

F. Naming Conventions of Variables
People who are used to MFC prefer Hungarian notation ). If you are used to this, use it, but be sure to be consistent with the people in the same project. In addition, some people are used to the lower-line method in C ++, which can also be used.
Hungarian Notation:
Sfirstname
Under score style:
_ Firstname
Here we provide a prefix naming convention for Hungarian Notation:
Int I
Byte B
Char C
Double D
Float F
Long L
Offset off
Length Len
Object o
String S (or Str)
Arbitray value v

6. Java File Format
There are many ways to define your file statement format. The following is an example:
A. File Header description (optional)
B. Package Definition
C. Empty rows
D. Import Statement
E. Empty rows
F. Class Definition
For example:

Package com. MIDI;

// Java classes
Import java. AWT .*;
Import java. Io .*;
Import javax. Swing. event .*;

// WebLogic classes
Import weblogic. Internal .*;

/**
* Blah
* @ Author MIDI
* @ Version 22.2
*/
Public class myfirst extends jframe {
...
}

/**
* FOO...
* @ Author MIDI
* @ Version 38.2
*/
Class Foo {
...
}

7. Import Order
The disorganized order looks unpleasant. You should classify the classes you want to import and list them in order:
A. java standard class (Java .*)
B. Java extension class (javax .*)
C. Third-party class
D. Your application class
Note that they are annotated in a third-party class to describe their source:
Import java .*;
Import java. util. date;
Import java. util. enumeration;
Import javax. SQL .*;

// Apache xerces
Import org. Apache. xml .*;
Import org. Apache. xerces. Dom .*;

// Application classes
Import com. Midi. util .*;

8. Order of Classes
A. javadoc comments or other file header comments
B. Class Declaration
C. Fields statement
D. Empty rows
E. Constructor
F. Empty rows
G. Method (excluding main)
H. Empty rows
I. inner class
J. Empty rows
K. Main ()
Example:
/**
* This is a simple DOM tree XML Parser...
*...
* @ Author: MIDI
* @ Version: 0.0.1
**/
Public class myparser {
// Public Constants

Public static final String title = "myparser ";
Public static final string version = "0.0.1 ";

// Private Variables
Private int ischemaversion;

/**
* Constructor
*/
Public myparser (){
Ischemaversion = 1;
}

/**
* Constructor
* @ Param...
*/
Public myparser (ischemaversion ){
This. ischemaversion = ischemaversion;
}

/**
* Initialize the parser...
*/
Public void myinit () throws exception {
....
}

/**
* Start the application
*/
Public static void main (string [] argvs ){
...
}
}

9. Field Definition
Follow these steps:
A. Public constant
B. Public variable
C. Protected constant
D. Protected variable
E. Package constant
F. Package variable
G. Private constant
H. Private variable

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.