Java project naming convention transfer order

Investigation of the Java project naming convention sun online documentation help documentation.

Transfer from the following: Trackback:

  • Level I: Default registration requirements for all projects in which all members adhere.
  • Level II: recommends that all projects comply with all the members.
  • Level III: to encourage the implementation of various projects based on the actual situation.

Use Tab indentation, rather than the space bar - the choice of characters to indent the right to leave 2,4,8 readers.

120 characters per line - because it is the era of 1024 * 768.

if, for, while only a single sentence statement, if the sentence to read may cause confusion, need to use "(" and ")" enclose, or can be omitted.

/ / Error, need to use curly braces () enclose
if (condition)
if (condition) doSomething ();
doSomething ();

  • Encountered abbreviations, such as XML, only the first letter capitalized, that is loadXmlDocument () rather than loadXMLDocument ()
  • Package name must be all lowercase, as far as possible using a single word
  • Interface names can be a noun or adjective (in addition to 'able', 'ible', or 'er' suffix), such as Runnable, Accessible.
    In order to interface-based programming, as I do not use initials or a name suffix with IF methods, such as IBookDao, BookDaoIF.
  • Local variables and input parameters with the class member variables with the same name do not (get / set methods and the exception constructor)
  • Modifier should be based on the following order: public, protected, private, abstract, static, final, transient, volatile, synchronized, native, strictfp.
  • The declaration order of classes and interfaces (available Eclipse's source-> sort members functionality that automatically order):
    1. Static member variable / Static Fields
    2. Static initialization block / Static Initializers
    3. Member Variables / Fields
    4. Initialization block / Initializers
    5. Constructor / Constructors
    6. Static member methods / Static Methods
    7. Member methods / Methods
    8. Type (internal class) / Types (Inner Classes)

The same type, according to public, protected, private order.


By / * ...* / defined in the standard C-Style's comments. Note has been dedicated to failure code.

/ *
* Comment out the code
* String s = "hello";
* System.out.println (s);
* /

By / / define the details of the code dedicated to comment, even if more than one line comments are also still in use / / to work with with the / ** / comments separate from the failure code

In addition to private variables, the end of the line is not recommended to use annotations.

class MyClass (

private int myField; / / An end-line comment.

public void myMethod (

/ / a very very long
/ / comment.
if (condition1) (
/ / condition1 comment
) Else (
/ / elses condition comment

  • Note the first sentence is necessary to (English) periods, question mark or exclamation mark the end. Javadoc tool will generate a note in the first sentence on the method of summary tables and index.
  • JavaDoc and the IDE, in order to be able to quickly link to jump to the associated classes and methods, as much as possible the use of @ see xxx.MyClass, @ see xx.MyClass # find (String).
  • Class must be @ author author name of their author, do not need to declare @ version and @ date, by a version management system to retain this information. (II)
  • If the Notes have more than one paragraph, use <p> separated. (II)
  • Sample code to <pre> </ pre> package. (II)
  • Logo (java keyword, class / method / field / argument name, Constants) to <code> </ code> package. (II)
  • Logo first appeared in (@ linkxxx.Myclass) in order to JavaDoc annotation can be linked with the IDE. (II)

Note Each word must have its essential meaning, not to write in comments "@ param name - the name of" Such nonsense.
If the comment is nonsense, along with label delete it, rather than automatically generate a bunch of empty tags, such as the empty @ param name, the empty @ return.

  • API function if it exists for the contract must state that it's pre-condition (precondition), postcondition (postcondition), and invariant (invariant). (II)
  • For a complex API calls as far as possible to provide code examples. (II)
  • Bug the need for known statement. (II)

If the method allows Null as a parameter, or allow the return value is Null, must be described in the JavaDoc.
If you did not say, method calls are not allowed to use the Null as a parameter, and that the return value is a Null Safe.

/ **
* Get the object.
* @ Return the object to found or null if not found.
* /
Object get (Integer id) (

  • The poor quality of the code but it can run properly, or not yet implemented the code with the / / TODO: or / / XXX: Statement
  • Hidden errors in the code with the / / FIXME: statement
  1. When faced with the unknown caller, the method requires the input verification parameters, such as incompatible with the throw IllegalArgumentException, recommend the use of Spring's Assert series of functions.
  2. Hiding tools of the constructor to ensure that only static methods and variables of the class can not be constructed
  3. Variable definition as far as possible concrete implementation based on interfaces rather than classes, such as the Map map = new HashMap ()
  4. The code can not use System.out.println (), e.printStackTrace (), must use the logger print information.
  1. To re-thrown exception must retain the original exception, that is, throw new NewException ( "message", e); but not written throw new NewException ( "message").
  2. In all exceptions are caught and there is no place must be thrown back to write the log.
  3. If the exception is a normal exception handling block must be empty comments explain why, otherwise, do not allow the empty catch block.
  4. Framework as far as possible to capture low-level exceptions, and packaged into a high-level exception to re-thrown, hiding the details of low-level exception. (III)
  • DAC do not measure no more than 7 (III)
    Explained: DAC (Data Abstraction Coupling) data abstraction coupling is to describe the coupling between objects of a code metrics. DAC measure, said there are instances of a class of the number of other classes.
  • CFO do not measure no more than 20 (III)
    Explained: CFO (Class Fan Out) type fan-out is to describe the coupling between classes as a code metrics. CFO measure, said a class depend on the number of other classes.
  • Too many method (constructor) parameters affect the readability of the code, or a sign of bad design. Consider the value of an object instead of these parameters, or re-design.
  • Method length of 150 lines or less (II)
    Long way to affect the readability of the code, or a method of bear signs of too much responsibility. The responsibility of the proposed split.
  • CC measure no more than 10 (III)
    Explained: CC (CyclomaticComplexity) Space complexity refers to a method of the number of independent paths can be used within a method if, while, do, for, catch, switch, case,?: The words with the operator of the total months &&,|| numbers to measure.
  • NPath measure no more than 200 (III)
    Explained: NPath measure, said the implementation of a method that may be the number of paths.
  • Boolean expression Boolean operators (&&,||) the number of not more than 3 (III)
  • if statement nested within the layer 3-layer (II)
  • File size less than 2000 lines (II)
    Impact of the code much more readable source files, or assumed too much responsibility for a class of signs, the proposed split the responsibility to another class.
  • Anonymous inner classes within the 20-line (II)
    Too long anonymous inner classes affect the code readability. Recommendation: Reconstruction of the name of the (general) internal class.
  1. Overloaded method must use the @ Override, can avoid the parent class method changes lead to overloaded function is invalid.
  2. Do not care about the warning report uses the @ SuppressWarnings ( "unused"), @ SuppressWarnings ( "unchecked"), @ SuppressWarnings ( "serial") commented out

Use and Inellij IDEA The code validation has been a lot of code that can be identified quality problems. Coupled with the use of Checkstyle , PMD , FindBugs Triple check, covering most of the code GuideLine.

  1. Eclipse: In Windows-> Preferences-> Java-Compiler-> Errors / Warnings in accordance with the rules of this document will open some of the original Ignore the rules.
  2. IDEA: In the Setting-> Errors in setting the rules, call Analyzer-> Inspece Code to check.
  3. CheckStyle: Installation of Eclipse plug-ins CheckStyle In Windows-> Preferences-> CheckStyle into springside team default in the / tools / codereviewer / springside_check.xml rules
  4. PMD: install PMD in Eclipse plug-in , Windows-> Preferences-> PMD remove all the rules of the original, import springside team by default in the / tools / codereviewer / springside_pmd.xml the RuleSet.
  5. FindBugs: Install FindBugs in Eclipse plug-ins , In the Project Properties -> FindBugs, the cancellation of the warning MS/EI/EI2 /, SnVI / SE / WS / RS, ST / NP / UwF / SS / UuF | UrF | SIC

5. References Sun's Coding Conventions

  1. Sun MicroSystem;
  2. The Elements of Java Style Scott W. Ambler wait;
  3. The rules of the code detection tools: CheckStyle , PMD , FindBugs

The following switched


Provided here, and describe the design, write code naming convention. All developers must be unconditionally

Compliance, and in accordance with the naming rules for naming. If inadequate, unreasonable, please come to, the project began

Before the correction. ※ This article does not specifically stated that the English letters and Arabic numerals are all half-width.

1. Basic Design Engineering

1.1. Screen Name

Item code [3] + Module code [3] + page numbers [2] A total of eight

Item Code [3]: THP [TongshidaHomePage]

Module code [3]: A01 [Home] B01 [Company], B02 [Company History],

Page numbers [2]: THPB0101 [About page],

THPC0101 [message board display the page],

THPC0102 [message board update the page],

※ figures began to increase from the 01, no 00 pages.

1.2. Database Name

Database name: Item code [3] + "DB" (THPDB)

Table name: English name lowercase easy to understand terms, such as userif, department field names:

Easy to understand the use of a number of lower-case English name. For example, userid, username, departid,

2. Detailed design work

2.1. Program name

1) Action program name: picture ID [8 Wei] + Action name [Several] +

(1) picture ID [8 bits]: Same as [1.1. Screen Name]

(2) Action name [Several]: at the beginning of capital letters.

Common name: at the beginning of uppercase, lowercase liberty behind the name:

(3) Action programs must eventually add [] to indicate it is the Action program.

(4) The final name examples:


[About Us page - the initial processing Action]

[About Us page - retrieve the information processing Action]

2) FormBean program name: picture ID [8 Wei] + Form name [Several] +

(1) picture ID [8 bits]: Same as [1.1. Screen Name]

(2) Form program named [Several]: at the beginning of capital letters. Common name: Free name:

(3) FormBean program must eventually add [] to indicate it is FormBean program.

(4) The final name examples:


[About Us page - the main content FormBean]

[About Us page - News search result set FormBean]

[Company Profile Page - Announcement search result set FormBean]

3. Code Project (PG Engineering)

3.1. Java package structure (directory structure)

1) The package name must be all lower case, here is the structure of package

/ com

/ tongshida

/ common

/ comp

/ db

/ comweb

/ THPB0101

/ action

/ form

/ THPC0101

2) [com.tongshida]: that this package the following is the company's total for all or Interpreter Interpreter of the company's total

Development, com the meaning of the company's

3) [com.tongshida.common]: This package following placement, you can with other projects is the future

Can be reused when developing programs. For example a common function and so on.

4) [com.tongshida.comweb]: placement can only be used inside the project development, and the future, do

The project can not be reused or difficult to Java programs. For example the specific business logic.

5) [com.tongshida.comcom.comp]: put the project in the future reusable common


6) [com.tongshida.comweb. Screen ID]: in order to screen as a unit, separated from the development of this item

The purpose of business logic part of the Java program.

7) [com.tongshida.comweb. Screen ID.action]: Place the screen moves to implement objects,

Action is the object (that is, Action of the Java files).

8) [com.tongshida.comweb. Screen ID.form]: Place the screen data FormBen Objects

(That is, ActionForm's Java files).

3.2. Import of the naming rules

1) Import allowed inside with [*], we should all use to all the objects listed here.

2) and Import has nothing to do, but to write SQL text select the text which does not allow the write select *, must be

Put out to retrieve field names Douxiechulai, a field or fields had to set out more than 100 words

Segment name. Cases) select username, password, age from userif can write

select * from userif

3.3. Object Name

1) object name (Class name) must be with the file name (java file) the same.

For example, file object must be


3.4. Variable naming rules

1) static final named constant:

(1) must be all caps

(2) the composition by a number of English words, we should underscore [_] Segmentation


2) from ordinary variable name:

(1) by a number of English words are constituted, at the beginning of the word should be lowercase, followed by the beginning of the word capitalized.

Cases) String userName = "Tom"

(2) for the use of loop variables in principle applicable to lower-case i, j, k.

Cases) for (int i = 0; i <sales.length; i + +)

3) object variable name:

(1) In principle, remove the screen ID, the first to use lower case letters.

Cases) THPB0101MainForm mainForm = new THPB0101MainForm ();

(2) as shown in the variable name the variable object name.

Cases) ResultSet newsListRs = new ResultSet ();

3.5. Method naming

1) at the beginning of the letters to lowercase, at the beginning of each word should be capitalized

2) at the beginning of the English word verb should start, followed by general words follow the noun in English

Cases) setName (), getPass ()

3) The name generally observe when you look at the symmetry of the verb word

add <=> remove, insert <=> delete, get <=> set, start <=> stop, begin <=> end,

send <=> receive, first <=> last, put <=> get, up <=> down, show <=> hide,

source <=> target, open <=> close, and so on ... there are also many other

3.6. JSP screen directory structure.

1) JSP directory structure.

/ Project name



/ THPA01



/ THPA02



3.7. Bad meaningless names.

1) Light with the following word in the naming.

Info amendments userInfo, guestInfo, studentInfo

Data revised newsDataRS (RS is a ResultSet)

There are names for the project name does not seem to be tough.

分类:Java 时间:2010-03-19 人气:619
blog comments powered by Disqus


iOS 开发

Android 开发

Python 开发



PHP 开发

Ruby 开发






Javascript 开发

.NET 开发



Copyright (C), All Rights Reserved. 版权所有 闽ICP备15018612号

processed in 5.692 (s). 10 q(s)