Java program code writing style and some simple considerations (

Source: Internet
Author: User
Tags class definition naming convention

1. The style must be consistency (consistent)
A fellow man with my nose asked, why does our Java code indentation format have to be this way, but not him, he is like his own, so he wrote the code is always in his own custom style. The results were killed in the Codereview and ordered to be modified. So he was very much disobedient. Is the consistency of style. In fact, his style, there is no problem, but in the project, and other programmers of the style of the program, it seems shut, there is a problem. For example, the indentation, such as the variable name method, different classes, different methods, each different, this program is very difficult to see. So once you've chosen a style, be sure to keep it consistent. If a project has a style, even if it does not conform to your own habits, it must be consistent, should not be unconventional.

2. Indent style (indent)
Since the indentation is speaking, the first thing to say is the indentation style; In general, Class C, like Java, uses indentation. And commonly used, there are four kinds of
A.k&r Style
This is the first indentation style of the C program, by the inventor of C Ritchie and his collaborators Kernighan pioneered the use of:
if (<cond>) {
<body>
}
It is characterized by curly braces and if judged on the same line. Typically, indents are 8 spaces or a TAB key, but in C + + and Java, 4 spaces are often indented. Some people like to use two spaces, stealing thought bad, not obvious.

B. BSD style
Also known as Allman Style, from the UNIX BSD programmer Eric allman--he wrote many programs for BSD:
if (<cond>)
{
<body>
}
Features: curly braces and conditional judgments are divided into two lines.

C. Whitesmith style
This style stems from Whitesmith C:
if (<cond>)
{
<body>
}


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

So what kind of good is it in Java? It is recommended to use a or B only. Sun has a Java Code Name convention, which is recommended by a.

3. tab or space (Tabs vs space)
or indentation issues. How much distance should one indent be? Is it eight spacebar, or is it a TAB key?

Java has a feature that is cross-platform. However, a cross-platform refers to its class that can run on a virtual machine on a different platform. Java's source programs, sometimes not cross-platform. What the? The source program can also not cross platform? Yes. Once a programmer sent some code, open in my environment, the program ugly Mess, there is the indentation of the place, no indentation, and some are indented a large section, like a rock, rugged and uneven. This kind of code quality can not! Asked the programmer to ask, replied that he was very beautiful, he also devoted time to beautify them?

Originally his indentation did not pay attention to a style, in some places with the TAB key, some places to play space. On some different platforms, the TAB key width is not the same.

Said here, I believe we are more clear, in the indentation, try not to tab, but with a space. Fortunately, many editors can define the TAB key on your keyboard as a few spaces. Go and define it quickly!

How many spaces do you use each time? 4 of them. 2 Too few are not obvious, 8 are too much to occupy space.

4. Line width
Said 8 space bar space, then I have 320 columns, 8 blank what? Stop! Please do not exceed 80 columns in one line. Many terminals a screen can only display 80 columns for them to think about bar. If your statement is too long, try to break it and write it in a few columns.

5. Variable naming
SUN Java Code Convention defines the naming conventions for package, class, method, and common variables in Java.

Naming rules for methods, variables, and constants

The naming conventions for packages, classes, and interfaces have been explained in the above chapters and are not covered here, this section explains the knowledge about methods, variables, and the naming conventions of constants in Java programming.

Naming rules for 1.10.1 methods

Methods are generally verbs, the first letter should be lowercase, in the case of multiple words mixed, the first word of all words after the first letter uppercase, the remaining letters lowercase, such as the following code:

Run ();

Runfast ();

Getbackground ();

In the declaration section of a method, you typically provide a description of the function of the method, and a description of the return value and parameter in the method, such as the following code:

public string ShowMessage (String message) {

...

//statements;

... ..

return Message ;

}

If the method is not recommended in the ongoing upgrade of the SOFTWARE PRODUCT, you can add the keyword @deprecated implementation in the comment section of the method declaration.

Naming rules for 1.10.2 variables

The naming convention for variables is that except for variables (variable), all instances of objects (instance), classes (Class) and the first letter of the class's constant (constant) should be lowercase, and the first letter of all words after the first word in case of multiple word blending is capitalized, The rest of the letters are outside the lowercase rules. The first letter of the variable is not either _ or $, even if the system allows it. The variable name is very compact and meaningful. The name of the variable should be easy to remember, easy to understand, even if the long interval can be known by its name. The variable name of a single character 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;

Naming rules for 1.10.3 constants

Constants in Java are typically named with uppercase words, and words are separated by underscores (_), which conform to the ANSI constant naming conventions, 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;

& Note the use of the keyword static and final will be discussed in detail in the following sections.

This paper discusses the code writing style in the Java language and related formatting and writing rules, the following is a simple Java programming practice, from which to master the knowledge learned.

1.11 Java Programming Practice

Four ways to explain Java program Design style and formatting rules, which is the basis for writing master-level code.

1.11.1 rules for accessing variables in instances and classes

In general, do not declare a variable in a class to be public, unless the design requires it, if the variable is not of a public type, it can only access the relevant variable by means of the common type method, such as the Getxx () method. If you create a class that doesn't have any behavioral methods, you'll have to declare the variables in the class as public (publicly) types for outside access.

1.11.2 rules for static variables and methods in reference classes

When you try to reference a static method or static member variable of a class in your code, do not refer to it through an instance object of the class, although this is allowed. You should refer to them by class, as shown in the following code:

public Staticclassmethod ();

Myclass.classmethod (); That's right

Myobject.classmethod (); Not correct (should be avoided)

1.11.3 variable Assignment rules

Try to avoid assigning multiple values to a variable in a single-line statement, which makes the code difficult to understand, such as the following code:

UserName = User1.name = ' Jerry Lin '; This type of assignment should be avoided as much as possible

Try to avoid assigning values to unary expressions, such as the following code is absolutely disallowed in Java:

if (i++ = m++) {

...

}

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

if ((c + + = d++)! = 0) {

...

}

Try to avoid nesting assignments, which can waste more time on the compiler, such as the following code:

D = (A = B + c) +r;

The above assignment should be modified to the following method:

A = B + C;

D = A + R;

1.11.4 General rules

1. Parentheses rules

You should try to use parentheses () to define the binding order of the expressions, avoid non-subjective intent errors due to operator precedence, even if you know more about operator precedence and the code looks clearer, but other programmers see this code as clearly as you do, such as the following code:

if (i = = j && m ==n)//should try to avoid

if ((i = = j) && (M = = N))//correct

2. return value rule

You should try to match the program structure to your intentions, for example:

if (isTrue) {

return true;

} else {

Returnfalse;

}

The above program has some "affected not pleasing" feeling, should be modified to:

return isTrue;

Similar there,

if (condition) {

RETURNX;

}

return y;

should be modified to:

return (condition x:y);

3. Special annotation Rules

You can represent your pseudocode in a program with some special annotations, for example, by using execute to indicate that the code is problematic but executable, using FIXME to indicate that the code has a problem and must not be executed, such as the following code:

if (isTrue) {

EXECUTE

int i = 0;

i++;

} else {

Fixme because I is not declared

i++;

}

So far, the code style and formatting rules about Java programming are all finished, I hope you in your own code to try to apply, the beginning of the application may not be very accustomed to, but as long as the persistence, I believe you will find a good code style for the design of the various benefits, and will gradually produce admiration and attachment.

Summary

This chapter explains in detail the Java program design style, including: Java file name and file organization structure, Java document Comment header, package declaration and reference, class and interface (interface) Declaration, Java source file Orchestration format, java program annotation, The declaration initialization and placement of variables, the rules of Java program Statement writing, the application of space and blank lines, and the naming rules of methods, variables and constants in Java programming are given in this chapter, and the three rules for ① access to instances and variables in classes are also presented. ② A rule that refers to static variables and methods in a class; ③ variable assignment rules). By learning the above knowledge, as long as you can adhere to the above writing rules, only from the code style you have the ability to write master Java code style, this is what you learn this chapter of the harvest. To continue to be close to the core of the master Java code, please continue to study the chapters in this book carefully.

Here are some caveats and some of the ways that Sun didn't mention but everyone used to.

A. Naming variables with meaningful names
First, name your variables with a complete English word or a conventional shorthand, such as:
FirstName
ZipCode
If English is not good enough, at least with other people can understand the pinyin named, such as
Zhuzhi (Address)
A random shorthand, or a random name, no one can understand the meaning of your variable:
Fn
Zc
Zz

B. Constants are named with all caps and draw lines
The constant in Java is the static final:
Static final smth_bbs= "bbs.tsinghua.edu.cn";

C. Naming collection class variables with complex numbers
Collection include arrays, vectors, and so on. When naming, use the plural:
Customers
Classmates
It can also be named with some modifiers:
Somestudents
Alldepartments

D. Cyclic variables
Generally everyone uses I, J, K and so on to do the cyclic variable.

E. Stream variable
General habits are used in and out as stream variables, corresponding to InputStream, OutputStream
Class. If you read and write the iostream, you can use InOut.

f. Naming conventions for variables
People who are accustomed to MFC prefer to use the Hungarian nomenclature (Hungarian Notation). If you're used to this, use it, but be careful to be consistent with project people. Some people are accustomed to C + + in the next line of the way, can also be used.
Hungarian Notation:
Sfirstname
Under Score Style:
_FirstName
Here is a prefix naming habit 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, here is an example:
A. File header description (none available)
B. Package definition
C. Blank Line
D. import statement
E. Empty lines
F. Class definition
Such as:

Package Com.midi;

Java Classes
Import java.awt.*;
Import java.io.*;
Import javax.swing.event.*;

WebLogic Classes
Import weblogic.internal.*;


public class Myfirst extends JFrame {
...
}


Class Foo {
...
}

7. Import Order
Disorderly order, looks very disagreeable. The classes that you want to import should be categorized in the order listed:
A. Java standard Class (java.*)
B. Java extension Class (javax.*)
C. Third-party classes
D. Your application's class
Also note that they are annotated in third-party classes, stating their origin:
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 declarations
C. Fields declaration
D. Blank Line
E. Constructors
F. Empty line
G. Methods (not including main)
H. Empty line
I. Inner class
J. Blank Line
K. Main ()
Cases:

public class Myparser {
Public constants

public static final String TITLE = "Myparser";
public static final String VERSION = "0.0.1";

Private variables
private int ischemaversion;


Public Myparser () {
Ischemaversion = 1;
}


Public Myparser (ischemaversion) {
This.ischemaversion = ischemaversion;
}


public void Myinit () throws Exception {
....
}


public static void Main (string[] Argvs) {
...
}
}

9. Field definition
Please follow the following order:
A. Public constants
B. Public variables
C. Protected often

Java program code writing style and some simple considerations (

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.