java coding standard - algomapeople.auc.ca/xu/cosc4506/kryptocodingstandard1-1.doc  · web...

22
Table of Contents 1 INTRODUCTION 3 1.1 PURPOSE 3 1.2 SCOPE 3 1.3 REFERENCES 3 2 NAMING CONVENTIONS 3 2.1 PACKAGES AND FILES 3 2.2 CONSTANTS 3 3 FORMATTING CONVENTIONS 3 3.1 CLASS FILE STRUCTURE 3 3.2 COMMENTS 3 3.2.1COMMENTS: CLASS HEADER 3 3.2.2COMMENTS: METHOD HEADER 3 3.2.3COMMENTS: FILE HEADER 3 3.3 INDENTATION 3 3.4 WHITE SPACE 3 3.4.1BLANK LINES 3 3.4.2BLANK SPACES 3 4 STATEMENTS 3 4.1 SIMPLE STATEMENTS 3 4.2 COMPOUND STATEMENTS 3 4.3 RETURN STATEMENT 3 4.4 IF, IF-ELSE, IF ELSE-IF ELSE STATEMENTS 3 4.5 FOR STATEMENTS 3 4.6 WHILE STATEMENTS 3 4.7 DO-WHILE STATEMENTS 3 4.8 SWITCH STATEMENTS 3 4.9 TRY-CATCH STATEMENTS 3 4.10 EXCEPTION STATEMENTS 3 4.10.1 THROWING AN EXCEPTION 3 4.10.2 CATCHING AN EXCEPTION 3 5 DECLARATIONS 3 i

Upload: others

Post on 23-Jul-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Java Coding Standard - Algomapeople.auc.ca/xu/Cosc4506/KryptoCodingStandard1-1.doc  · Web viewIntroduction. This document contains the Java coding standard that the Krypto team

Table of Contents

1 INTRODUCTION 3

1.1 PURPOSE 31.2 SCOPE 31.3 REFERENCES 3

2 NAMING CONVENTIONS 3

2.1 PACKAGES AND FILES 32.2 CONSTANTS 3

3 FORMATTING CONVENTIONS 3

3.1 CLASS FILE STRUCTURE 33.2 COMMENTS 33.2.1 COMMENTS: CLASS HEADER 33.2.2 COMMENTS: METHOD HEADER 33.2.3 COMMENTS: FILE HEADER 33.3 INDENTATION 33.4 WHITE SPACE 33.4.1 BLANK LINES 33.4.2 BLANK SPACES 3

4 STATEMENTS 3

4.1 SIMPLE STATEMENTS 34.2 COMPOUND STATEMENTS 34.3 RETURN STATEMENT 34.4 IF, IF-ELSE, IF ELSE-IF ELSE STATEMENTS 34.5 FOR STATEMENTS 34.6 WHILE STATEMENTS 34.7 DO-WHILE STATEMENTS 34.8 SWITCH STATEMENTS 34.9 TRY-CATCH STATEMENTS 34.10 EXCEPTION STATEMENTS 34.10.1 THROWING AN EXCEPTION 34.10.2 CATCHING AN EXCEPTION 3

5 DECLARATIONS 3

5.1 NUMBER PER LINE 35.2 INITIALIZATION 35.3 PLACEMENT 35.4 CLASS AND INTERFACE DECLARATIONS 3

6 Code Example 3

i

Page 2: Java Coding Standard - Algomapeople.auc.ca/xu/Cosc4506/KryptoCodingStandard1-1.doc  · Web viewIntroduction. This document contains the Java coding standard that the Krypto team

1 Introduction

This document contains the Java coding standard that the Krypto team will follow during the development of Netscape Database Keystore Version 2.0 (NDBS 2.0).

This coding standard should be updated after each TSP cycle, or as needed. Code inspection results are expected to be a good source of additional material for this document.

1.1 PurposeCoding conventions help ensure that project code has a consistent structure and style. They are intended to make the code easier to read, understand, review, and maintain.

This document is intended for the following uses:

Desk-side reference for NDBS 2.0 developers during coding Source for code review checklists Reference for developers who must extend and maintain the NDBS 2.0 project

1.2 ScopeThis document describes the following for the Krypto Project:

Naming conventions for projects, files, objects, variables, and other code constructs Formatting conventions for code modules and their comments Error handling conventions Coding practices and recommendations

1.3 ReferencesThe following sources were used in creation of the original version of this standard.

Coding Conventions for the Java Programming Language, http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html

Gryphon Coding Standard version 0.4

Java Coding Standard Version 2.0 of the computer science department at RIT, http://www.cs.rit.edu/~fyj/java-coding-standard.html

JavaDoc Tool, http://java.sun.com/j2se/javadoc/index.html

1

Page 3: Java Coding Standard - Algomapeople.auc.ca/xu/Cosc4506/KryptoCodingStandard1-1.doc  · Web viewIntroduction. This document contains the Java coding standard that the Krypto team

2 Naming ConventionsMeaningful names are important for maintaining understandable, high-quality code. Developers should take the time to choose names that are descriptive and unambiguous.

Except for user-defined constants, all identifier names should be written as a mix of upper and lower case letters. Krypto uses the following rules for formatting identifier names:

Identifier type Naming rules ExampleVariables Variables are in mixed case with a

lowercase first letter. Internal words start with capital letters. Variable names should not start with underscore ‘_’ or dollar sign ‘$’ characters, even though both are allowed. Variable names should be short yet meaningful. The choice of a variable name should be mnemonic- that is, designed to indicate to the casual observer the intent of its use. One-character variable names should be avoided except for temporary "throwaway" variables. Common names for temporary variables are i, j, k, m, and n for integers; c, d, and e for characters.

int i;char c;float myWidth;

Packages The prefix of a unique package name is always written in all-lowercase ASCII letters and should be one of the top-level domain names, currently com, edu, gov, mil, net, org, or one of the English two-letter codes identifying countries as specified in ISO Standard 3166, 1981. Subsequent components of the package name vary according to an organization's own internal naming conventions. Such conventions might specify that certain directory name components be division, department, project, machine, or login names. The prefix for an NDBS package will be edu.cmu.sei.cbs.ndbs.

edu.cmu.sei.cbs.ndbs

Classes Class names should be nouns, in mixed case with the first letter of each internal word capitalized. Try to keep your class names simple and descriptive. Use whole words-avoid acronyms and abbreviations (unless the abbreviation is much more widely used than the long form, such as URL or HTML).

class Raster;class ImageSprite;

2

Page 4: Java Coding Standard - Algomapeople.auc.ca/xu/Cosc4506/KryptoCodingStandard1-1.doc  · Web viewIntroduction. This document contains the Java coding standard that the Krypto team

Constants (user defined) Capitalize all letters in each word.Use underscores in place of spaces.

static final int MIN_WIDTH = 4;

Methods Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized.

run();runFast();

Interfaces Interface names should be capitalized like class names.

interface Storing;

2.1 Packages and Files

This section describes the naming conventions for development files created in the Java project.

These files will be named according to the following rules:

File type Naming rules ExampleSource files The same as the class name in the file. Hash.java

Compressed package files Name should be capitalized like class names.

Hash.jar

The following file extensions will be used for all Krypto files.

File type ExtensionJava source file javaJava class file classJava compressed package file

jar

2.2 Constants

Use the static keyword to declare constants. Use constants to avoid hard-coded values in the code. For user-defined constants, use uppercase letters and replace spaces with underscores to format the name of the

constant.

static String DSN_NAME = "Krypto_cafe";String strDSN; strDSN = DSN_NAME;

3

Page 5: Java Coding Standard - Algomapeople.auc.ca/xu/Cosc4506/KryptoCodingStandard1-1.doc  · Web viewIntroduction. This document contains the Java coding standard that the Krypto team

3 Formatting Conventions

The length of Java source lines, including comments, should not exceed 80 characters.

Use liberal amounts of white space to improve code readability.

When a complete statement or an expression will not fit on a single line, break it according to these general principles: 

1. Break after a comma.  2. Break before an operator.  3. Prefer higher-level breaks to lower-level breaks.  4. Align the new line with the beginning of the expression at the same level on the previous line.  5. If the above rules lead to confusing code or to code that's all up against the right margin, indent one

additional level. 

3.1 Class File Structure

The elements of a class or interface file should appear in the following order:

1. Class (static) variables 2. Instance variables  3. Constructors  4. Methods grouped by functionality

3.2 Comments

The formatting for comments will follow the requirements of the JavaDoc Tool. A documentation comment is made up of two parts -- a description followed by zero or more tags, with a blank line (containing a single asterisk "*") between these two sections: 

/**  * This is the description part of a doc comment * * @tag    Comment for the tag */

The first line is indented to line up with the code below the comment, and starts with the begin-comment symbol (/**) followed by a return. 

Subsequent lines start with an asterisk *. They are indented an additional space so the asterisks line up. A space separates the asterisk from the descriptive text or tag that follows it. 

Insert a blank comment line between the description and the list of tags, as shown. 

Insert additional blank lines to create "blocks" of related tags. 

The last line begins with the end-comment symbol (*/) indented so the asterisks line up and followed by a return. Note that the end-comment symbol contains only a single asterisk (*). 

4

Page 6: Java Coding Standard - Algomapeople.auc.ca/xu/Cosc4506/KryptoCodingStandard1-1.doc  · Web viewIntroduction. This document contains the Java coding standard that the Krypto team

A blank line should precede and follow the comment block.

3.2.1 Comments: Class Header

The following comments will appear before the definition of every class.

/**  * A description of what the class does.  *  * @author      Author name  * @author      Contributor 1  * @author      Contributor 2                 .                 .  * @author      Contributor n  */

3.2.2 Comments: Method Header

The following comments will appear before every method (including main).

/** * A description of what the method does * * @param       name    description * @param       name    description                .                . * @param       name    description * * @return              description * * @exception   name    description * @exception   name    description                 .                 . * @exception   name    description * * <PRE> * preconditions * </PRE> * * <POST> * postconditions * </POST> * */Definition of comments

@paramThe @param tag is followed by the name (not type) of the parameter, followed by a description of the parameter. Additional spaces should be inserted between the name and description so that comments line up in a block. Dashes or other punctuation should not be inserted before the description. The name always starts

5

Page 7: Java Coding Standard - Algomapeople.auc.ca/xu/Cosc4506/KryptoCodingStandard1-1.doc  · Web viewIntroduction. This document contains the Java coding standard that the Krypto team

with a lowercase letter. The description is most usually a phrase, starting with a lowercase letter and ending without a period, unless it contains a complete sentence. 

@return  The @return tag is followed by a description of the return value. Whenever possible, detailed information (such as returns -1 when an out-of-bounds argument is supplied) should be provided. Spaces should be used to line the description up with the rest of the comments in the method. 

@exception  An @exception tag should be included for at least any declared (checked) exceptions. It can also document any non-declared exceptions that can be thrown by the method, (normally those that appear directly in the implementation, rather than those that are indirectly thrown). 

<PRE> </PRE>JavaDoc does not have a tag for preconditions, so an HTML tag is used. Preconditions should be expressed in prose or in a formal language if it is more appropriate for the situation.

<POST> </POST>JavaDoc does not have a tag for postconditions, so an HTML tag is used. Postconditions should be expressed in prose or in a formal language if it is more appropriate.

3.2.3 Comments: File Header

Each Java source file contains a single public class or interface. The root name of the file will be the name of the public class that it contains and the suffix will be .java.

Any non-public classes in the source file must provide services that are used directly by the public class (such non-public classes may also be used by other public classes in the same package).

All Java Source files must begin with a C-style comment that lists the file name and version information: 

/*  * filename.java  *  * Version:  *     $Id$  *  * Revisions:  *     $Log$  */

3.3 Indentation

Four spaces should be used as the unit of indentation

3.4 White Space

3.4.1 Blank Lines

Blank lines improve readability by setting off sections of code that are logically related.

Two blank lines should always be used in the following circumstances:

Between sections of a source file Between class and interface definitions

6

Page 8: Java Coding Standard - Algomapeople.auc.ca/xu/Cosc4506/KryptoCodingStandard1-1.doc  · Web viewIntroduction. This document contains the Java coding standard that the Krypto team

One blank line should always be used in the following circumstances:

Between methods Between the local variables in a method and its first statement Before a block or single-line comment Between logical sections inside a method to improve readability

3.4.2 Blank Spaces

Blank spaces should be used in the following circumstances:

A keyword followed by a parenthesis should be separated by a space. Example:

while (true) { ... }

Note that a blank space should not be used between a method name and its opening parenthesis. This helps to distinguish keywords from method calls.

A blank space should appear after commas in argument lists.

All binary operators should be separated from their operands by spaces. Blank spaces should never separate unary operators such as unary minus, increment ("++"), and decrement ("--") from their operands. Example:

a += c + d; a = (a + b) / (c * d);

while (d++ = s++) { n++; } printSize("size is " + foo + "\n");

The expressions in a for statement should be separated by blank spaces. Example:

for (expr1; expr2; expr3)

Casts should be followed by a blank space. Examples:

myMethod((byte) aNum, (Object) x); myMethod((int) (cp + 5), ((int) (i + 3)) + 1);

7

Page 9: Java Coding Standard - Algomapeople.auc.ca/xu/Cosc4506/KryptoCodingStandard1-1.doc  · Web viewIntroduction. This document contains the Java coding standard that the Krypto team

4 Statements

4.1 Simple Statements

Each line should contain at most one statement. Example:

argv++; // Correctargc--; // Correct argv++; argc--; // INCORRECT!

4.2 Compound Statements

Compound statements are statements that contain lists of statements enclosed in braces "{ statements }". See the following sections for examples.

The enclosed statements should be indented one more level than the compound statement.

The opening brace should be at the end of the line that begins the compound statement; the closing brace should begin a line and be indented to the beginning of the compound statement.

Braces are used around all statements, even single statements, when they are part of a control structure, such as an if-else or for statement. This makes it easier to add statements without accidentally introducing bugs due to forgetting to add braces.

4.3 Return Statement

A return statement with a value should not use parentheses unless it is an expression that requires parentheses or the parentheses provide clarity. Example:

return;return myDisk.size();return (size ? size : defaultSize);

4.4 if, if-else, if else-if else Statements

The if-else class of statements should have the following form:

if (condition) { statements;}

if (condition) { statements;} else { statements;}

8

Page 10: Java Coding Standard - Algomapeople.auc.ca/xu/Cosc4506/KryptoCodingStandard1-1.doc  · Web viewIntroduction. This document contains the Java coding standard that the Krypto team

if (condition) { statements;} else if (condition) { statements;} else{ statements;}

Note: if statements always use braces {}. Avoid the following error-prone form:

if (condition) //INCORRECT !! statement;

4.5 For Statements

A for statement should have the following form:

for (initialization; condition; update) { statements;}

An empty for statement (one in which all the work is done in the initialization, condition, and update clauses) should have the following form:

for (initialization; condition; update);

When using the comma operator in the initialization or update clause of a for statement, avoid the complexity of using more than three variables. If needed, use separate statements before the for loop (for the initialization clause) or at the end of the loop (for the update clause).

4.6 While Statements

A while statement should have the following form:

while (condition) { statements;}

An empty while statement should have the following form:

while (condition);

4.7 do-while Statements

A do-while statement should have the following form:

do { statements;} while (condition);

9

Page 11: Java Coding Standard - Algomapeople.auc.ca/xu/Cosc4506/KryptoCodingStandard1-1.doc  · Web viewIntroduction. This document contains the Java coding standard that the Krypto team

4.8 switch Statements

A switch statement should have the following form:

switch (condition) {case ABC: statements; /* falls through */

case DEF: statements; break;

case XYZ: statements; break;

default: statements; break;}

Every time a case falls through (doesn't include a break statement), add a comment where the break statement would normally be. This is shown in the preceding code example with the /* falls through */ comment. Every switch statement should include a default case. The break in the default case is redundant, but it prevents a fall-through error if later another case is added.

4.9 try-catch Statements

A try-catch statement should have the following format:

try { statements;} catch (ExceptionClass e) { statements;}

A try-catch statement may also be followed by finally, which executes regardless of whether or not the try block has completed successfully.

try { statements;} catch (ExceptionClass e) { statements;} finally { statements;}

10

Page 12: Java Coding Standard - Algomapeople.auc.ca/xu/Cosc4506/KryptoCodingStandard1-1.doc  · Web viewIntroduction. This document contains the Java coding standard that the Krypto team

4.10 Exception Statements

4.10.1 Throwing An Exception

When throwing an exception, the statement should have the following sample format:

public void OpenKeyStore(String path) throws java.security.KeyStoreException { BerkeleyDBManager cert7 = new BerkeleyDBManager();

try { cert7.hashOpen(path + “cert7.db”); } catch (java.io.IOException e) { throw new java.security.KeyStoreException("Certificate file not found in given path."); } }

A precise description of the exception should be included while throwing an exception. The text should be as simple and direct as possible, and end with a period. Uppercase is mandatory in the first word of the sentence, and should be used inside the sentence only when required.

Examples of correct exception text are:

“Capability for deleting certificates not implemented yet.”“Incorrect password for keystore file.”“Certificate file not found in given path.”

Examples of incorrect exception text:

“We’re sorry, but we have not implemented the capability to delete entries at the moment.”“Incorrect password.”“Certificate file not there.”

4.10.2 Catching An Exception

When catching an exception, the statement should have the following sample format:

try { OpenKeyStore(“c:\ndbs\”); } catch (java.security.KeyStoreException e) { System.out.println(e.getMessage()); }

The catch statement should only print the message supplied by the method throwing the exception.

11

Page 13: Java Coding Standard - Algomapeople.auc.ca/xu/Cosc4506/KryptoCodingStandard1-1.doc  · Web viewIntroduction. This document contains the Java coding standard that the Krypto team

5 Declarations

5.1 Number Per Line

Maximum one declaration per line is mandatory. The comment describing each variable should be placed above the declaration.

// Indentation level int level;

// Size of tableint size;

The following is not allowed:

int level, size;

Do not put different types on the same line. Example:

int foo, fooArray[]; // INCORRECT!

5.2 Initialization

Local variables should be initialized where they are declared. The only reason not to initialize a variable where it is declared is if the initial value depends on some computation occurring first.

5.3 Placement

Declarations should be placed only at the beginning of blocks. Do not wait to declare variables until their first use; it can confuse the unwary programmer and hamper code portability within the scope.

void myMethod() {// beginning of method block int int1 = 0;

if (condition) {// beginning of "if" block int int2 = 0; ... }}

The one exception to the rule is indexes of for loops, which in Java can be declared in the for statement:

for (int i = 0; i < maxLoops; i++) { ... }

Avoid local declarations that hide declarations at higher levels. For example, do not declare the same variable name in an inner block:

12

Page 14: Java Coding Standard - Algomapeople.auc.ca/xu/Cosc4506/KryptoCodingStandard1-1.doc  · Web viewIntroduction. This document contains the Java coding standard that the Krypto team

int count;...myMethod() { if (condition) { int count = 0; // INCORRECT! ... } ...}

5.4 Class and Interface Declarations

When coding Java classes and interfaces, the following formatting rules should be followed:

No space between a method name and the parenthesis "(" starting its parameter list, followed by the parenthesis “)”

Open brace "{" appears at the end of the same line as the declaration statement.

Closing brace "}" starts a line by itself indented to match its corresponding opening statement, except when it is a null statement the "}" should appear immediately after the "{".

class Sample extends Object { int ivar1; int ivar2;

Sample(int i, int j) { ivar1 = i; ivar2 = j; }

int emptyMethod() { }

...}

Methods are separated by a blank line .

13

Page 15: Java Coding Standard - Algomapeople.auc.ca/xu/Cosc4506/KryptoCodingStandard1-1.doc  · Web viewIntroduction. This document contains the Java coding standard that the Krypto team

6 Code Example

The following example shows how to format a Java source file containing a single public class.

/* * Blah.java *  * Version:  *     1.82 99/03/18  *  * Revisions:  *     $Log$  * * * Copyright (c) 1994-1999 Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A. * All rights reserved. * * This software is the confidential and proprietary information of Sun * Microsystems, Inc. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in * accordance with the terms of the license agreement you entered into * with Sun. */

package java.blah;

import java.blah.blahdy.BlahBlah;

/** * Class description goes here. * * @author Firstname Lastname */public class Blah extends SomeClass { /* A class implementation comment can go here. */

/** classVar1 documentation comment */ public static int classVar1;

/** * classVar2 documentation comment that happens to be * more than one line long */ private static Object classVar2;

/** instanceVar1 documentation comment */ public Object instanceVar1;

/** instanceVar2 documentation comment */ protected int instanceVar2;

/** instanceVar3 documentation comment */ private Object[] instanceVar3;

14

Page 16: Java Coding Standard - Algomapeople.auc.ca/xu/Cosc4506/KryptoCodingStandard1-1.doc  · Web viewIntroduction. This document contains the Java coding standard that the Krypto team

/** * ...constructor Blah documentation comment... */ public Blah() { // ...implementation goes here... }

/** * ...method doSomething documentation comment... */ public void doSomething() { // ...implementation goes here... }

/** * ...method doSomethingElse documentation comment... * @param someParam description */ public void doSomethingElse(Object someParam) { // ...implementation goes here... }}

15