Ministry of education and training fpt university



tải về 1.87 Mb.
trang6/24
Chuyển đổi dữ liệu09.10.2016
Kích1.87 Mb.
#32639
1   2   3   4   5   6   7   8   9   ...   24

IV. Coding convention


1. Purpose

This document describes rules and recommendations for developing applications and class libraries using the Java and Language. The goal is to define guidelines to enforce consistent style and formatting and help developers avoid common pitfalls and mistakes. This document is a collection of standards, conventions and guidelines for writing Java and C# code that is easy to understand, to maintain, and to enhance.


2. Java language

2.1. Program Structure

This section lists commonly used file suffixes and names.



2.1.1. File Suffixes

Java Software uses the following file suffixes:



File Type

Suffix

Java source

.java

Java bytecode

.class

2.1.2. Common File Names

Frequently used file names include:



File Name

Use

README

The preferred name for the file that summarizes the contents of a particular directory.


2.2. Indentation And Braces

2.2.1. Tab and Indent

Four spaces should be used as the unit of indentation.

Tab characters should be avoided because different editors interpret tabs differently.

Continuation indent should be configured to 8 spaces (two normal indentation levels).



2.2.2. Braces

Open curly brace “{” of class/method declarations and other code blocks should be at “END OF LINE” of the first statement of code block.



2.2.3. Line Length

Avoid lines longer than 80 or 120 characters, since they're not handled well by many terminals and tools.



Note: Examples for use in documentation should have a shorter line length-generally no more than 70 characters.

2.3. Comments

Java programs can have two kinds of comments: implementation comments and documentation comments. Implementation comments are those found in C++, which are delimited by /*...*/, and //. Documentation comments (known as "doc comments") are Java-only, and are delimited by /**...*/. Doc comments can be extracted to HTML files using the javadoc tool.

Implementation comments are mean for commenting out code or for comments about the particular implementation. Doc comments are meant to describe the specification of the code, from an implementation-free perspective to be read by developers who might not necessarily have the source code at hand.

Comments should be used to give overviews of code and provide additional information that is not readily available in the code itself. Comments should contain only information that is relevant to reading and understanding the program. For example, information about how the corresponding package is built or in what directory it resides should not be included as a comment.


Discussion of nontrivial or non-obvious design decisions is appropriate, but avoid duplicating information that is present in (and clear from) the code. It is too easy for redundant comments to get out of date. In general, avoid any comments that are likely to get out of date as the code evolves.

2.3.1. Implementation Comment Formats

Programs can have four styles of implementation comments: block, single-line, trailing, and end-of-line.



2.3.1.1 Block Comments

Block comments are used to provide descriptions of files, methods, data structures and algorithms. Block comments may be used at the beginning of each file and before each method. 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 describe.

A block comment should be preceded by a blank line to set it apart from the rest of the code.

/*


* Here is a block comment.

*/


2.3.1.2 Single-Line Comments

Short 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 .A single-line comment should be preceded by a blank line. Here's an example of a single-line comment in Java

if (condition) {

// Handle the condition.

...

}

2.3.1.3 Trailing Comments



Very short comments can appear on the same line as the code they describe, but should be shifted far enough to separate them from the statements. If more than one short comment appears in a chunk of code, they should all be indented to the same tab setting.

Here's an example of a trailing comment in Java code:

if (a == 2) {

return TRUE; // special case

} else {

return isPrime(a); // works only for odd a

}

2.3.1.4 End-Of-Line Comments

The // comment delimiter can comment out a complete line or only a partial line. It shouldn't be used on consecutive multiple lines for text comments; however, it can be used in consecutive multiple lines for commenting out sections of code. Examples of all three styles follow:

if (foo > 1) {

// Do a double-flip.

...

} else {


return false; // Explain why here.

}

2.4. Declarations



2.4.1 Number Per Line

One declaration per line is recommended since it encourages commenting. In other words,

int level; // indentation level

int size; // size of table

is preferred over

int level, size;

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

int foo, fooarray[]; //WRONG!



Note: The examples above use one space between the type and the identifier. Another acceptable alternative is to use tabs, e.g.:

int level; // indentation level

int size; // size of table

Object currentEntry; // currently selected table entry



2.4.2 Array Declaration

Though Java supports two styles of array declarations, we should only follow one as following:

int anIntArray[]; // AVOID

int[] anIntArray; // RECOMMENDED



2.4.3 Initialization

Try to initialize local variables where they're declared. The only reason not to initialize a variable where it's declared is if the initial value depends on some computation occurring first.



2.4.4 Placement

Put declarations only at the beginning of blocks. (A block is any code surrounded by curly braces "{" and "}".) Don't wait to declare variables until their first use; it can confuse the unwary programmer and hamper code portability within the scope.

void myMethod() {

int int1 = 0; // beginning of method block

if (condition) {

int int2 = 0; // beginning of "if" block

...

}

}



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

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

tempString = ...;

...


}

Local variables used inside loops should be declared outside and right before the loop statement, as shown in above example.

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

int count;

...

myMethod() {



if (condition) {

int count = 0; // AVOID!

...

}

...



}

2.4.5 Class and Interface Declarations

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

Opening bracket "{" always appears at end of line.

Closing bracket "}" should appear on a new line.

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



2.5. Statements

2.5.1 Simple Statements

Each line should contain at most one statement. Example:

argv++; // Correct

argc--; // Correct

argv++; argc--; // AVOID!

2.5.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 a if-else or for statement. This makes it easier to add statements without accidentally introducing bugs due to forgetting to add braces.

2.5.3 Return Statements

A return statement with a value should not use parentheses unless they make the return value more obvious in some way. Example:

return;

return myDisk.size();

return (size ? size : defaultSize);

2.5.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;

}
if (condition) {



statements;

} else if (condition) {



statements;

} else {



statements;

}

2.5.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).



2.5.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);

2.5.7 Do-while Statements

A do-while statement should have the following form:

do {

statements;

} while (condition);



2.5.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.

2.5.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;

}



2.6 White Space

Blank spaces should be used in the following circumstances:



  • A keyword followed by a parenthesis should be separated by a space

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 except. 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);



2.7 Naming Conventions

Naming conventions make programs more understandable by making them easier to read.

They can also give information about the function of the identifier-for example, whether it's a constant, package, or class-which can be helpful in understanding the code.

2.7.1 General Rules

This section outlines the rules to be followed while naming Source File / variable / control / method.



  1. Programmer defined names should be functionally meaningful, and should indicate the purpose of the file / variable / control / method in question.

  2. Use terminology applicable to the domain.

If your users refer to their clients as customers, then use the term Customer for the class, not Client.

Many developers will make the mistake of creating generic terms for concepts when perfectly good terms already exist in the industry/domain.



  1. Identifiers must be as short as possible without obscuring their meaning, preferably 20 characters

or less. Excessively long variable names are cumbersome and irritating for programmers to use, hence chances of error during coding are higher.

iv. Avoid names that are similar or differ only in case.

For example, the variable names persistentObject and persistentObjects should not be used together, nor should anSqlDatabase and anSQLDatabase


  1. Avoid cryptic names, even in case of scratch pad variables or counters.

Bad or cryptic names waste programmer effort. Time is spent in just understanding the role of the variable/control/method rather than in understanding functionality or solving a problem.

  1. Abbreviations in names should be avoided.

Domain specific phrases that are more naturally known through their acronym or abbreviations should be kept abbreviated.

computeAverage(); // NOT: compAvg();

generateHTML(); // NOT: generateHypertextMarkupLanguage();

Unambiguous abbreviations should be used wherever possible. For example, use custName instead of customerName. Capitalize the whole abbreviation.



  1. The method name should not contain any special characters other than underscore.

Use underscores only while naming constants (see below)

2.7.2 Class/Interface

Each class/interface name must start with uppercase and respect the general rules of above naming convention , e.g. class CustomerBean.



  • Exception classes should be suffixed with Exception, e.g. LMSFunctionalException.

  • Interfaces having no method should be prefixed with I, e.g. IConstants.

  • Abstract classes should be prefixed with Abstract, e.g. abstract class AbstractBean.

  • Implementation classes should be suffixed with Impl, e.g. class CustomerBOImpl implements CustomerBO.



2.7.3 Variables

  • Each variable name must start with lowercase and respect the general rules of naming convention , e.g. custName.

  • List variables (of type Collection/List) should be suffixed with List, e.g. Collection custList.

  • Set variables (of type Set/HashSet) should be suffixed with Set, e.g. Set custSet = new HashSet();

  • Map variables (of type Map/HashMap/TreeMap) should be suffixed with Map, e.g. Map custMap = new TreeMap();

  • Array variables can be suffixed with Array, e.g. int[] custIDArray;

  • The use of ID or Id should be consistent throughout an application.

2.7.4 Constants

The following guidelines should be followed while naming constants:



  • Respect the general rules of naming convention .

  • All constants to be named in uppercase letters, with underscore between words.

  • All constants must be declared as static final.

2.7.5 Methods

The following guidelines to be followed while naming methods in class files:



  • Respect the general rules of naming convention

  • Method name must start with lowercase letter.

  • Usually use “active verb” as the first word of method name. Here are some common verbs:

getCustomerID, setCustomerID

isActive, hasAddresses

findCustomers, searchCustomers

computeSalary, calculateSalary

initializeParameters, initParameters

addCustomer, removeCustomer

insertCustomer, deleteCustomer

updateCustomer, modifyCustomer, amendCustomer

openConnection, closeConnection, saveFile

createBuffer, destroyBuffer

startProcess, stopProcess


  • Verbs should be used by pairs and should be used consistently throughout an application.

  • Some special methods not starting with verbs:

Factory methods: newCustomer(), newCustomerBO()

Conversion methods: toString(), toLongPhoneNumber(), toXXX()

3. C# language

3.1 Description

This section contains tables describing a high-level summary of the major standards covered in this document. These tables are not comprehensive, but give a quick glance at commonly referenced elements.



Naming Conventions

c” = camel Case

P” = Pascal Case

_” = Prefix with _Underscore



“x = Not Applicable.

Identifier

Public

Protected

Internal

Private

Notes

Project File

P

x

x

x

Match Assembly & Namespace.

Source File

P

x

x

x

Match contained class.

Other Files

P

x

x

x

Apply where possible.

Namespace

P

x

x

x

Partial Project/Assembly match.

Class or Struct

P

P

P

P

Add suffix of subclass.

Interface

P

P

P

P

Prefix with a capital I.

Generic Class [C#v2+]

P

P

P

P

Use T or K as Type identifier.

Method

P

P

P

P

Use a Verb or Verb-Object pair.

Property

P

P

P

P

Do not prefix with Get or Set.

Field

P

P

P

_c

Only use Private fields.

No Hungarian Notation!

Constant

P

P

P

_c



Static Field

P

P

P

_c

Only use Private fields.

Enum

P

P

P

P

Options are also PascalCase.

Delegate

P

P

P

P



Event

P

P

P

P



Inline Variable

x

x

x

c

Avoid single-character and enumerated names.

Parameter

x

x

x

c




Coding Style

Code

Style

Source Files

One Namespace per file and one class per file.

Curly Braces

On new line. Always use braces when optional.

Indention

Use tabs with size of 4.

Comments

Use // or /// but not /* … */ and do not flowerbox.

Variables

One variable per declaration.



Language Usage

Code

Style

Native Data Types

Use built-in C# native data types vs .NET CTS types.

(Use int NOT Int32)



Enums

Avoid changing default type.

Generics [C#v2+]

Prefer Generic Types over standard or strong-typed classes.

Properties

Never prefix with Get or Set.

Methods

Use a maximum of 7 parameters.

base and this

Use only in constructors or within an override.

Ternary conditions

Avoid complex conditions.

foreach statements

Do not modify enumerated items within a foreach statement.

Conditionals

Avoid evaluating Boolean conditions against true or false.

No embedded assignment.

Avoid embedded method invocation.


Exceptions

Do not use exceptions for flow control.

Use throw; not throw e; when re-throwing.

Only catch what you can handle.

Use validation to avoid exceptions.

Derive from Exception not Application Exception.


Events

Always check for null before invoking.

Locking

Use lock() not Monitor. Enter().

Do not lock on an object type or “this”.

Do lock on private objects.


Dispose() & Close()

Always invoke them if offered, declare where needed.

Finalizers

Avoid.

Use the C# Destructors.

Do not create Finalize() method.


AssemblyVersion

Increment manually.

ComVisibleAttribute

Set to false for all assemblies.




tải về 1.87 Mb.

Chia sẻ với bạn bè của bạn:
1   2   3   4   5   6   7   8   9   ...   24




Cơ sở dữ liệu được bảo vệ bởi bản quyền ©hocday.com 2024
được sử dụng cho việc quản lý

    Quê hương