Coding Standards
V 1.4 (rev. 9/20/2005)
Table of Contents
1. Introduction
1.1. Purpose of this document
This
document details coding standards for .NET projects and best practices as they
apply to Chetu. These are Internal Guidelines and should be made part of the
existing Boot Camp period for all developers and architects that develop
software using this technology. The main purpose of the document is to specify
a broad framework and backbone that unifies software coding conventions,
readability and presentation across our company.
1.2. How it should be interpreted
Good
practice does not mean that the knowledge described should always be applied
uniformly on all projects; the customer and/or project team is responsible for
determining what is appropriate for any given project. Additionally, as part of
our Corporate Culture of “Do whatever makes sense”, care should be taken during
interpretation of this document and its purpose. It must be ensured that these standards
by themselves do not become a “bottleneck”.
The
guidelines are “work in progress” and should be improvised regularly. The
document should be kept brief and to the point to maintain simplicity without
killing flexibility and innovation.
2. File Organization
2.1. C# Source files
Keep
your classes/files short, don't exceed 2000 LOC, divide your code up, make
structures clearer. Put every class in a separate file and name the file like
the class name (with .cs as extension of-course). This convention makes things
much easier.
2.2. Directory Layout
Create
a directory for every namespace. (For MyProject.TestSuite.TestTier use
MyProject/TestSuite/TestTier as the path, do not use the namespace name with
dots). This makes it easier to map namespaces to the directory layout.
3. Indentation
3.1. Wrapping Lines
When
an expression will not fit on a single line, break it up according to these
general principles:
·
Break after a comma.
·
Break after an operator.
·
Prefer higher-level breaks to lower-level breaks.
·
Align the new line with the beginning of the expression at the
same level on the previous line
Example
of breaking up method calls:
longMethodCall(expr1, expr2,
expr3, expr4, expr5);
expr3, expr4, expr5);
Examples
of breaking an arithmetic expression:
PREFER:
var = a * b / (c - g + f) +
4 * z;
BAD STYLE – AVOID:
var = a * b / (c - g +
f) + 4 * z;
var = a * b / (c - g + f) +
4 * z;
BAD STYLE – AVOID:
var = a * b / (c - g +
f) + 4 * z;
The first is preferred, since the break occurs outside the
paranthesized expression (higher level rule). Note that you indent with tabs to
the indentation level and then with spaces to the breaking position in our
example this would be:
> var = a * b / (c - g + f) +
> ......4 * z;
Where
'>' are tab chars and '.' are spaces (the spaces after the tab char are the
indent with of the tab). A good coding practice is to make the tab and space
chars visible in the editor which is used.
3.2. White Spaces
An
indentation standard using spaces never was achieved. Some people like 2
spaces, some prefer 4 and others die for 8, or even more spaces. Better use
tabs. Tab characters have some advantages:
·
Everyone can set their own preferred indentation level
·
It is only 1 character and not 2, 4, 8 … therefore it will reduce
typing (even with smart indenting you have to set the indentation manually
sometimes, or take it back or whatever)
·
If you want to increase the indentation (or decrease), mark one
block and increase the indent level with Tab with Shift-Tab you decrease the
indentation. This is true for almost any text editor.
Here,
we define the Tab as the standard indentation character.
Don't use spaces for indentation - use tabs!
4. Comments
4.1. Block Comments
Block
comments should usually be avoided. For descriptions use of the /// comments to
give C# standard descriptions is recommended. When you wish to use block
comments you should use the following style:
/* Line 1
* Line 2
* Line 3
*/
As
this will set off the block visually from code for the (human) reader.
Alternatively you might use this old-fashioned C style for single line
comments, even though it is not recommended. In case you use this style, a line
break should follow the comment, as it is hard to see code preceded by comments
in the same line:
/* blah blah blah */
Block
comments may be useful in rare cases, refer to the TechNote 'The fine Art of
Commenting' for an example. Generally block comments are useful for comment out
large sections of code.
4.2. Single Line Comments
You
should use the // comment style to "comment out" code (SharpDevelop
has a key for it, Alt+/). It may be used for commenting sections of code too.
Single
line comments must be indented to the indent level when they are used for code
documentation. Commented out code should be commented out in the first line to
enhance the visibility of commented out code.
A
rule of thumb says that generally, the length of a comment should not exceed
the length of the code explained by too much, as this is an indication of too
complicated, potentially buggy, code.
4.3. Documentation Comments
In
the .net framework, Microsoft has introduced a documentation generation system
based on XML comments. These comments are formally single line C# comments
containing XML tags. They follow this pattern for single line comments:
/// <summary>
/// This class...
/// </summary>
Multi-line
XML comments follow this pattern:
/// <exception
cref=”BogusException”>
/// This exception gets thrown as
soon as a
/// Bogus flag gets set.
/// </exception>
All
lines must be preceded by three slashes to be accepted as XML comment lines.
Tags fall into two categories:
·
Documentation items
·
Formatting/ Referencing
The
first category contains tags like <summary>, <param> or
<exception>. These represent items that represent the elements of a
program's API which must be documented for the program to be useful to other
programmers. These tags usually have attributes such as name or cref as
demonstrated in the multi-line example above. These attributes are checked by
the compiler, so they should be valid. The latter category governs the layout
of the documentation, using tags such as <code>, <list> or
<para>. Documentation can then be generated using the 'documentation'
item in the #develop 'build' menu. The documentation generated is in HTMLHelp
format. For a fuller explanation of XML comments see the Microsoft .net
framework SDK documentation. For information on commenting best practice and
further issues related to commenting, see the TechNote 'The fine Art of
Commenting'.
5. Declarations
5.1. Number of Declarations per Line
One
declaration per line is recommended since it encourages commenting1. In other
words,
int level; // indentation level
int size; // size of table
Do
not put more than one variable or variables of different types on the same line
when declaring them. Example:
int a, b; //What is 'a'? What
does 'b' stand for?
The
above example also demonstrates the drawbacks of non-obvious variable names. Be
clear when naming variables.
5.2. Initialization
Try to initialize local variables as soon as they are declared.
For example:
string name = myObject.Name;
or
int val = time.Hours;
Note: If you initialize a dialog try to use the using statement:
using (OpenFileDialog
openFileDialog = new OpenFileDialog()) {
...
}
5.3. Class and Interface Declarations
When
coding C# classes and interfaces, the following formatting rules should be
followed:
·
No space between a method name and the parenthesis " ("
starting its parameter list.
·
The opening brace "{" appears in the next line after the
declaration statement
·
The closing brace "}" starts a line by itself indented
to match its corresponding opening brace.
For
example:
Class MySample : MyClass,
IMyInterface
{
int
myInt;
public
MySample(int myInt)
{
this.myInt
= myInt ;
}
void
Inc()
{
++myInt;
}
void
EmptyMethod()
{
}
}
6. Statements
6.1. Simple Statements
Each
line should contain only one statement.
6.2. Return Statements
A
return statement should not use outer most parentheses.
Don't use:
return (n * (n + 1) / 2);
use:
return n * (n + 1) / 2;
6.3. If, if-else, if else-if else Statements
if,
if-else and if else-if else statements should look like this:
if (condition) {
DoSomething();
...
}
if (condition) {
DoSomething();
...
} else {
DoSomethingOther();
...
}
if (condition) {
DoSomething();
...
} else if (condition) {
DoSomethingOther();
...
} else {
DoSomethingOtherAgain();
...
}
6.4. For / Foreach Statements
A for statement should have following form:
for (int i = 0; i < 5; ++i) {
...
}
or single lined (consider using a while statement instead) :
for (initialization; condition;
update) ;
A foreach should look like :
foreach (int i in IntList) {
...
}
Note: Generally use brackets even if there is only one statement
in the loop.
6.5. While / do-while Statements
A while statement should be written as follows:
while (condition) {
...
}
An
empty while should have the following form:
while (condition) ;
A do-while statement should have the following form:
do {
...
} while (condition);
6.6. Switch Statements
A switch statement should be of following form:
switch (condition) {
case A:
...
break;
case B:
...
break;
default:
...
break;
}
6.7. Try-catch Statements
A
try-catch statement should follow this form:
try {
...
} catch (Exception) {}
or
try {
...
} catch (Exception e) {
...
}
or
try {
...
} catch (Exception e) {
...
} finally {
...
}