Java Code Conventions

Java Code Conventions

Lượt xem: 118,950Lượt tải: 6Số trang: 24

Mô tả tài liệu

Why Have Code Conventions Code conventions are important to programmers for a number of reasons: • 80% of the lifetime cost of a piece of software goes to maintenance. • Hardly any software is maintained for its whole life by the original author. • Code conventions improve the readability of the software, allowing engineers to understand new code more quickly and thoroughly. • If you ship your source code as a product, you need to make sure it is as well packaged and clean as any other product you create....

Tóm tắt nội dung

12, 1997, Sun Inc. All rights Garcia Avenue, Mountain View, document is protected by No part of this document may be in any form by any prior written of Sun and its if any. The described in this document may be protected by one or more U.S. patents, foreign patents, Sun Sun the Sun Logo, SunXTL, JavaSoft, JavaOS, the JavaSoft Logo, Views, picoJava, JDBC, the Java Cup and Steam Logo, “Write Once, Run Anywhere” and Solaris are or of Sun Inc. in the United other ® is a trademark in the United States and other licensed through ® is a trademark of Adobe Systems, is a trademark of Netscape other product names mentioned herein are the of their DOCUMENT IS PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS BUT NOT LIMITED TO, THE IMPLIED OF FOR A PURPOSE, OR DOCUMENT COULD INCLUDE TECHNICAL OR ARE ADDED TO THE HEREIN; THESE CHANGES WILL IN NEW EDITIONS OF THE DOCUMENT. SUN INC. MAY AND/OR CHANGES IN THE AND/OR THE DESCRIBED IN AT ANY 2, 1997 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.1 Why Have Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 2 File Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 2.1 File Suffixes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 2.2 Common File Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 3 File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 3.1 Java Source Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 3.1.1 Beginning Comments. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 3.1.2 Package and Import . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 3.1.3 Class and Interface . . . . . . . . . . . . . . . . . . . . . . . . . . 3 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 4.1 Line Length . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 4.2 Wrapping Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 5 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 5.1 Comment Formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 5.1.1 Block Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 5.1.2 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 5.1.3 Trailing Comments. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 5.1.4 Comments. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 5.2 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 6.1 Number Per Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 6.2 Placement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 6.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 6.4 Class and Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 7.1 Simple . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 7.2 Compound . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 7.3 return . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 7.4 if, if-else, . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 7.5 for . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 7.6 while . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 7.7 do-while . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 7.8 switch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 7.9 try-catch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 8 White Space . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 8.1 Blank Lines. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 8.2 Blank Spaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 9 Naming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 10 Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 10.1 Providing Access to Instance and Class Variables . . . . . . . . . . . . . . . . . . . 2, 1997 10.2 Referring to Class Variables and Methods . . . . . . . . . . . . . . . . . . . . . . . . . 16 10.3 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 10.4 Variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 10.5 Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 10.5.2 Returning Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 10.5.3 before ‘?’ in the Operator. . . . . . . . . . . 17 10.5.4 Special Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 11 Code Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 11.1 Java Source File Example. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . - File Code - 1.1 Why Have Code are important to for a number of 80% of the lifetime cost of a piece of software goes to Hardly any software is for its whole life by the original Code improve the of the software, allowing engineers new code more quickly and If you ship your source code as a product, you need to make sure it is as well clean as any other product you create. 1.2 document reflects the Java language coding standards presented in the Java from Sun Major are from Peter King, Mike DeMoney, Jonni Kanerva, Kathy Walrath, and Scott questions or of this document, our copyright notice at on this document should be submitted to our feedback form at - File section lists commonly used file suffixes and - File - File 2.1 File uses the following file 2.2 Common File used file names - File file consists of sections that should be separated by blank lines and an optional each longer than 2000 lines are and should be an example of a Java program properly see “Java Source File Example” on 3.1 Java Source Java source file contains a single public class or When private classes are with a public class, you can put them in the same source file as class. The public class should be the first class or interface in the source files have the following Beginning comments (see Comments” on page 4) • Package and Import for Class and interface (see “Class and Interface on page 4) File Type source bytecode Name The preferred name for use gnumake to build our The preferred name for the file that of a - File Beginning source files should begin with a c-style comment that lists the the date, notice, and also a brief of the purpose of the program. For * * Version info * * Copyright notice */ 3.1.2 Package and Import first line of most Java source files is a package After can follow. For Class and Interface following table describes the parts of a class or interface in the order that appear. See “Java Source File Example” on page 19 for an example that of Notes 1 Comments” on page 9 on what should be in this class or interface if comment should contain any that wasn’t for the Class (static) variables First the public class then the and then the Instance variables First public, then and then - - spaces should be used as the unit of The exact of the vs. tabs) is Tabs must be set exactly every 8 spaces (not 4). 4.1 Line lines longer than 80 since they’re not handled well by many terminals Examples for use in should have a shorter line no more than 70 4.2 Wrapping an will not fit on a single line, break it according to these general Break after a comma. • Break before an Prefer breaks to Align the new line with the beginning of the at the same level on the If the above rules lead to confusing code or to code that’s squished up against the just indent 8 spaces are some examples of breaking method = Methods These methods should be grouped by rather than by scope or a private class method can be two public instance methods. The goal is to make reading and the code of - are two examples of breaking an The first is since the break occurs outside the which is at a higher = longName2 * + longName4 - + 4 * // = longName2 * + - + 4 * // are two examples of indenting method The first is the The second would shift the second and third lines to the far right if it used so instead it indents only 8 anArg, Object String Object { 8 SPACES TO AVOID VERY DEEP static anArg, Object String Object { wrapping for if should generally use the 8-space rule, since (4 space) makes seeing the body For USE THIS && || && && { //BAD WRAPS //MAKE THIS LINE EASY TO THIS && || && && { USE THIS if && || && && { are three ways to format ternary = ? beta : = ? beta : = ? beta : - - programs can have two kinds of comments: comments comments. comments are those found in C++, which by /*...*/, and //. comments (known as “doc and are delimited by /**...*/. Doc comments can be extracted to HTML the javadoc comments are mean for out code or for comments about Doc comments are meant to describe the of the an to be read by who might not the source code at should be used to give overviews of code and provide that is not readily available in the code itself. Comments should contain only that to reading and the program. For example, about how package is built or in what directory it resides should not be included as of or design decisions is but avoid that is present in (and clear from) the code. It is too easy for redundant get out of date. In general, avoid any comments that are likely to get out of date as the The frequency of comments sometimes reflects poor quality of code. When you to add a comment, consider rewriting the code to make it should not be enclosed in large boxes drawn with asterisks or other should never include special such as form-feed and 5.1 Comment can have four styles of comments: block, trailing Block comments are used to provide of files, methods, data Block comments should be used at the beginning of each file and before They can also be used in other places, such as within methods. Block comments inside a function or method should be indented to the same level as the code they block comment should be preceded by a blank line to set it apart from the rest of the comments have an asterisk “*” at the beginning of each line except the * Here is a block comment. */ 7 5 - comments can start with /*-, which is by indent(1) as the beginning of a block comment that should not * Here is a block comment with some very special * that I want indent(1) to ignore. * * one * two * three */ Note: If you don’t use you don’t have to use /*- in your code or make any to the that someone else might run indent(1) on your also Comments” on page 9. 5.1.2 comments can appear on a single line indented to the level of the code that follows. If a comment can’t be written in a single line, it should follow the block comment format 5.1.1). A comment should be preceded by a blank line. Here’s an a comment in Java code (also see Comments” on page 9): if { /* Handle the */ Trailing short comments can appear on the same line as the code they describe, but should far enough to separate them from the If more than one short in a chunk of code, they should all be indented to the same tab setting. Avoid language style of every line of code with a trailing an example of a trailing comment in Java code (also see page 9): if (a == 2) { return TRUE; /* special case */ } else { return /* works only for odd a // comment delimiter begins a comment that continues to the newline. It can a complete line or only a partial line. It shouldn’t be used on multiple lines for text comments; however, it can be used in multiple lines for of code. Examples of all three styles - (foo > 1) { // Do a return false; // Explain why (bar > 1) { // // // Do a return false; 5.2 See “Java Source File Example” on page 19 for examples of the comment further details, see “How to Write Doc Comments for Javadoc” which on the doc comment tags (@return, @param, further details about doc comments and javadoc, see the javadoc home page comments describe Java classes, methods, and fields. Each is set inside the comment /**...*/, with one comment per API. should appear just before the * The Example class provides ... */ class Example { that classes and are not indented, while their members are. The first line of doc comment (/**) for classes and is not indented; doc comment have 1 space of (to align the Members, have 4 spaces for the first doc comment line and 5 spaces you need to give about a class, variable, or method that for use an block comment (see section 5.1.1) (see section 5.1.2) comment after the For example, the of a class should go in in such an block the class not in the class doc comments should not be inside a method or Java comments with the first after the - - 6.1 Number Per Line One per line is since it In other level; // level int size; // size of table is preferred over int level, size; In no case should variables and functions be declared on the same line. dbaddr, // not put different types on the same line. foo, The examples above use one space between the type and the is to use tabs, level; // level int size; // size of // currently selected table entry 6.2 only at the beginning of blocks. (A block is any code by “{” and “}”.) Don’t wait to declare variables until their first use; it can confuse and hamper code within the { int int1; // beginning of method block if { int int2; // beginning of "if" block ... } } The one exception to the rule is indexes of for loops, which in Java can be declared in the (int i = 0; i < maxLoops; i++) { local that hide at higher levels. For example, do not declare the same variable name in an inner - { if { int count; // AVOID! ... } ... } 6.3 to local variables where they’re declared. The only reason not to where it’s declared is if the initial value depends on some occurring first. 6.4 Class and Interface coding Java classes and the following rules should be No space between a method name and the “(“ starting its parameter list • Open brace “{” appears at the end of the same line as the Closing brace “}” starts a line by itself indented to match its except when it is a null statement the “}” should appear after Sample extends Object { int ivar1; int ivar2; i, int j) { ivar1 = i; ivar2 = j; } int {} ... } • Methods are separated by a blank line 7 - 7.1 Simple line should contain at most one argc--; // - not use the comma operator to group multiple unless it is for an obvious (err) { “error”), exit(1); //VERY 7.2 Compound are that contain lists of enclosed in braces “{ }”. See the following sections for The enclosed should be indented one more level than the compound The opening brace should be at the end of the line that begins the compound brace should begin a line and be indented to the beginning of the Braces are used around all even when they are part of a such as a if-else or for This makes it easier to add bugs due to to add braces. 7.3 return return statement with a value should not use unless they make the return obvious in some way. (size ? size : 7.4 if, if-else, if-else class of should have the following form: if else else if else if - if always use braces {}. Avoid the following form: if //AVOID! THIS OMITS THE BRACES 7.5 for for statement should have the following update) empty for statement (one in which all the work is done in the clauses) should have the following using the comma operator in the or update clause of a for avoid the of using more than three If needed, use separate for loop (for the clause) or at the end of the loop (for the update 7.6 while while statement should have the following empty while statement should have the following 7.7 do-while do-while statement should have the following form: do while 7.8 switch switch statement should have the following - White { case /* falls through */ case time a case falls through (doesn’t include a break add a comment where the break statement would normally be. This is shown in the preceding code example with the /* falls through */ switch statement should include a default case. The break in the default case but it prevents a error if later another case is added. 7.9 try-catch try-catch statement should have the following catch e) - White Space 8.1 Blank lines improve by setting off sections of code that are logically blank lines should always be used in the following Between sections of a source file • Between class and interface blank line should always be used in the following Between Between the local variables in a method and its first Before a block (see section 5.1.1) or (see section 5.1.2) - Naming Between logical sections inside a method to improve 8.2 Blank spaces should be used in the following A keyword followed by a should be separated by a space. while (true) { ... } Note that a blank space should not be used between a method name and its This helps to keywords from method calls. • A blank space should appear after commas in argument lists. • All binary operators except . should be separated from their operands by spaces. should never separate unary operators such as unary minus, increment (“++”), (“--”) from their operands. a += c + d; a = (a + b) / (c * d); while (d++ = s++) { n++; } is " + foo + "\n"); • The in a for statement should be separated by blank spaces. (expr1; expr2; expr3) • Casts should be followed by a blank. aNum, (Object) x); (cp + 5), ((int) (i + 3)) + 1); 9 - Naming make programs more by making them easier to can also give about the function of the example, whether it’s package, or can be helpful in the given in this section are high level. Further are given at (to - - 10.1 Providing Access to Instance and Class make any instance or class variable public without good reason. Often, don’t need to be set or that happens as a side effect of method Type Rules for Naming Class names should be nouns, in mixed case with the first letter of each internal word Try to keep your class names Use whole and (unless the is much more widely used than the long form, such as URL or Interface names should be Methods should be verbs, in mixed case with the first letter with the first letter of each internal word Except for all instance, class, and class constants are in mixed case with a first letter. Internal words start with capi- tal names should be short yet The choice of a variable name should that is, designed to indicate to observer the intent of its use. variable names should be avoided temporary Com- mon names for temporary variables are i, j, k, m, and n for integers; c, d, and e for i; char The names of variables declared class and of ANSI constants should be with words separated by (“_”). (ANSI constants should for ease of MIN_WIDTH = 4; int MAX_WIDTH = 999; int = - example of public instance variables is the case where the class is a data with no behavior. In other words, if you would have used a struct instead of a class (if Java supported struct), then it’s to make the class’s instance 10.2 Referring to Class Variables and using an object to access a class (static) variable or method. Use a class name 10.3 constants should not be coded directly, except for -1, 0, and 1, which in a for loop as counter values. 10.4 Variable assigning several variables to the same value in a single It is hard to = = 'c'; // not use the operator in a place where it can be easily confused with the (c++ = d++) { // AVOID! Java be written as if ((c++ = d++) != 0) { ... } Do not use embedded in an attempt to improve run-time This is the job of the compiler, and besides, it rarely actually helps. = (a = b + c) + r; // be written as a = b + c; d = a + - 10.5 is generally a good idea to use liberally in involving mixed avoid operator problems. Even if the operator seems clear to you, it might not be to shouldn’t assume that other know as well as you do. if (a == b && c == d) // ((a == b) && (c == d)) // Returning to make the structure of your program match the intent. { return TRUE; } else { return instead be written { return be written ? x : before ‘?’ in the an a binary operator appears before the ? in the ternary ?: operator, it should be >= 0) ? x : Special XXX in a comment to flag something that is bogus but works. Use FIXME to flag is bogus and - Code - Code 11.1 Java Source File following example shows how to format a Java source file a single public are formatted For more see “Class and on page 4 and Comments” on page 9 /* * %W% %E% Firstname Lastname * * Copyright (c) 1993-1996 Sun Inc. All Rights * * This software is the and of Sun * Inc. You shall not * disclose such and shall use it only in * with the terms of the license agreement you entered into * with Sun. * * SUN MAKES NO OR ABOUT THE OF * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED * TO THE IMPLIED OF FITNESS FOR A * PURPOSE, OR SUN SHALL NOT BE LIABLE FOR * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR * THIS SOFTWARE OR ITS * Class goes here. * * @version 1.10 04 Oct 1996 * @author Firstname Lastname */ public class Blah extends SomeClass { /* A class comment can go here. */ /** classVar1 comment */ public static int /** * classVar2 comment that happens to be * more than one line long */ private static Object /** comment */ public Object /** comment */ protected int /** comment */ private Object[] - Code Examples /** * ...method Blah */ public Blah() { // goes here... } /** * ...method */ public void { // goes here... } /** * ...method * @param someParam */ public void { // goes here... 12, 1997 1 1 1.1 Why Have Code 1 1.2 1 2 File Names 1 2.1 File Suffixes 2 2.2 Common File Names 2 3 File 2 3.1 Java Source Files 2 3.1.1 Beginning Comments 3 3.1.2 Package and Import 3 3.1.3 Class and Interface 3 4 4 4.1 Line Length 4 4.2 Wrapping Lines 4 5 Comments 6 5.1 Comment Formats 6 5.1.1 Block Comments 6 5.1.2 Comments 7 5.1.3 Trailing Comments 7 5.1.4 Comments 7 5.2 Comments 8 6 9 6.1 Number Per Line 9 6.2 Placement 9 6.3 10 6.4 Class and Interface 10 7 10 7.1 Simple 10 7.2 Compound 11 7.3 return 11 7.4 if, if-else, 11 7.5 for 12 7.6 while 12 7.7 do-while 12 7.8 switch 12 7.9 try-catch 13 8 White Space 13 8.1 Blank Lines 13 8.2 Blank Spaces 14 9 Naming 14 10 Practices 15 10.1 Providing Access to Instance and Class Variables 15 10.2 Referring to Class Variables and Methods 16 10.3 Constants 16 10.4 Variable 16 10.5 Practices Returning Values before ‘?’ in the Operator Special Comments 17 11 Code Examples 18 11.1 Java Source File Example 18 Java Code - Why Have Code - File File Common File Names 3 - File Java Source Beginning Package and Import Class and Interface - Line Wrapping Lines 5 - Comment Block Trailing - Number Per Line 6.2 Class and Interface - Simple Compound return if, if-else, for while do-while switch try-catch - White Blank Blank - Naming - Providing Access to Instance and Class Referring to Class Variables and Variable Returning before ‘?’ in the Special - Code Java Source File