Swinburne .NET Coding Standard
From SwinBrain
The Swinburne .NET Coding Standard is based upon the ECMA 334 C# standard. The guidelines for coding standards is available on the MSDN.
Identifier Naming
This section outlines the different rules related to the naming of identifiers in Visual Basic .NET and C# programs that follow the Swinburne Coding Standard. This includes capitalisation, word choice,
Capitalisation
| Identifier Type | Case | Notes | Example |
|---|---|---|---|
| Class | Pascal Case | ArrayList | |
| Attribute Class | Pascal Case | Use Attribute suffix | SerializableAttribute |
| Exception Class | Pascal Case | Use Exception suffix | InvalidOperationException |
| Constant | All Uppercase | HEIGHT | |
| Enumeration type | Pascal Case | ShipType | |
| Event | Pascal Case | Click | |
| Interface | Pascal Case | Add a I prefix | IComparable |
| Local Variable | Camel Case | myList | |
| Method | Pascal Case | Add | |
| Namespace | Pascal Case | System | |
| Private Instance Field | Pascal Case | Prefix with an underscore (_) | _Tokens |
| Property | Pascal Case | Count | |
| Public Instance Field | Pascal Case | Avoid | Count |
| Protected Instance Field | Pascal Case | Avoid, prefix with an underscore (_) | _Tokens |
| Parameter | Camel Case | value |
Word Choice
- Do not use names that require case sensitivity to be distinguished.
- Avoid using class names that duplicate heavily used namespaces such as the System, Collections, Forms, IO namespaces.
- Avoid using abbreviations in identifiers. Example: UI should be UserInterface.
Namespaces
Namespaces are generally named using company name followed by product or technology name, for example Microsoft.Office.
- Do prefix namespaces with your company name or student id (use S123456)
- Do use Pascal Case and separate logical components using periods for example Murray.Services.CatalogueServices.
- Do use plural namespace names where appropriate. Example: System.Collections for plural use vs. System.Collections.Generic
- Do not have namespaces and classes with the same name
Classes
- Do use nouns or noun phrases
- Avoid using abbreviations
- Do not use any prefixes
- Do not use underscores
Interfaces
- Do use nouns, noun phrases, or adjectives describing behaviour
- Avoid using abbreviations
- Do prefix with the letter I
- Do not use underscores
- Do name standard implementation classes and interfaces similarly, for example IComponent and Component.
Enumerations
- Avoid using abbreviations
- Do not use Enum, or any other, suffix
- Do use singular names
- Do use plural name for bit fields
- Do' use the Flags attribute if the numeric values are meant to be ORed together
- Do not use enumerations for open sets such as product version, etc.
Static Members
- Do name static members with noun, noun phrases, or abbreviations for nouns.
- Do not use any prefixes
Parameters
- Do use descriptive names such that the parameter's name and type clearly identify its purpose
- Do not use prefixes
Methods
- Do use verbs or verb phrases
- Do not use get and set methods, use properties
Properties
- Do use nouns or noun phrases
- Do consider using the same name as the property type where appropriate, eg. Color property of type Color enumeration
- Do use indexers to access elements within a container
Events
- Do consider naming events with a verb
- Do use a EventHandler suffix for delegates used for event handling
- Do use two parameters named sender and e. The sender is an object that references the object that raised the event. The e parameter contains additional event argument information.
- Do use a EventArgs suffix for event argument classes such as MouseEventArgs.
Code Documentation
All non-private members must include XML documentation.
Type headers
This applies to classes, interfaces, delegates, enumerations, and structures written in C# and Visual Basic .NET.
Public types must include a concise summary that outlines the purpose and use of the type. This should be followed by detailed remarks that describe the function and use of the type. This documentation should aim to include everything a user will need to write code that make use of the type. Sample code may be included in a example section.
/// <summary> /// A concise paragraph describing the class's purpose and use. /// </summary> /// <remarks> /// <para>A more detailed overview of the type in question.</para> /// <para>Organise into one or more paragraphs and lists:</para> /// <list type=""table""> /// <listheader> /// <term>Employee</term> /// <description>Employee Type</description> /// </listheader> /// <item> /// <term>XXXX</term> /// <description>Administrator</description> /// </item> /// <item> /// <term>YYYY</term> /// <description>User</description> /// </item> /// </list> /// </remark> /// <example> /// Include text to describe the example. /// <code>Add code into the example</cod e> /// </example> public class Name { }
Method headers
All public and protected methods should include an XML comment that includes at least the summary, param, and returns entries. It is strongly recommended that methods include exception tags for exceptions that are expected to be thrown as there is no other way for developers to find this information.
/// <summary> /// One paragraph description of method. /// </summary> /// <param name="value">Short detail of parameter</param> /// <returns>Details of return value</returns> /// <exceptions cref="System.InvalidOperationException"> /// Details of when/why this is thrown</exception> public int Method(int value) {}
Single line comments
- Do use the // for single line comments.
- Do not use /* */ for single line comments.
Control Structures
General
The use of braces is required for almost all control structures. The exception is a single statement in an ‘if’ statement. The braces always appear on a line by themselves and are always aligned with the beginning of the keyword.
The code within the braces is always indented. The indentation quantum should be the same throughout the set of software, preferably 4 spaces, no less than 2.
Avoid using ‘continue’ and ‘break’ in loops.
Always use a default in switch statements. Use a break to end all cases in a switch statement.
while
The while statement should have the following form:
while (condition) { statements; }
for
for (int i = initial; i < max; i++) { statements; }
do
do { statements; } while (condition);
if
The if statement does not require braces where there is a single statement.
if (condition) statement; //or if (condition) { statements; }
if (condition) statement; else statement; //or if (condition) { statements; } else { statements; }
if(condition) statement; else if(condition) statement; else statement; //or if (condition) { statements; } else if (condition) { statements; } else { statements; }
switch
switch (int_expression) { case int_value_1: statement_1; statement_2; break; case int_value_2: statements; break; ... default: statements; }
exception handling
try { statements; } catch (exception_class name) { statements; }
If the catch does nothing, treat it like an empty method body, i.e.
{}
ne comments
- Do put short comments on the same line as the code they describe.
Statement Layout
Operators
The operators (+ - =) and the relational operators (== != etc) require a space on either side. The multiplicative operators (* / %) usually have a space on either side. There are circumstances when, to improve readability, some of these spaces are omitted.
Continuation
When a statement that is already indented exceeds 80 characters, the statement should be split over more than one line and the continuation lines should be indented by more than the indentation quantum.
The split should be before or after an operator. Preferably align similar parts of expressions under one another.
Examples
aName = Console.ReadLine(“Enter the name for student “ + (numberOfStudents + 1) + “: “); // counts from 1 aName = Console.ReadLine(“Enter the name for student “ + (numberOfStudents + 1) + “: “); // counts from 1 return groupName + “, “ + roomNumber + “, “ + teacherName + “, “ + numberOfStudents + “ students“; return groupName + “, “ + roomNumber + “, “ + teacherName + “, “ + numberOfStudents + “ students“; theGroup = new HomeGroup(“12K“, “ES304“, “K Gilgamesh“, numberOfStudents);
Forbidden
The following are forbidden.
goto, ++, -- and = within expressions
Example:
int x = 10; if(x++ > 10)//incorrect { //statments } if(x > 10)//correct { //statments } x++;
Visibility
Features of classes should have specified visibility (public/private/protected/internal(friend in Visual Basic.NET)/protected internal (protected friend in Visual Basic .NET) as appropriate. Instance variables should be private (use protected properties).
A class is marked as public only when necessary.
Example
/// <summary> /// Branch is a finite collection of accounts. Accounts may be retrieved by /// position (index in array). Also supports query of the account with /// maximum or minimum balance. /// </summary> class Branch { private int _MaxItems; private Account[] _BranchAccount; private int _BranchItems; private string _Name; public Branch(string aName, int maxAccounts) { _Name = aName; _MaxItems = maxAccounts; _BranchAccount = new Account[maxItems]; _BranchItems = 0; } /// <summary> /// If room, creates an account and adds it to the collection, else /// prints an error. /// </summary> /// <param name="customerName">the customers name as a string</param> /// <param name="initDeposit">the initial deposit as a double</param> /// <exception cref="System.ApplicationException">Thrown when the maximum /// number of accounts have been reached</exception> public void AddAccount(String customerName, double initDeposit) { if(branchItems < maxItems) { branchAccount[branchItems] = new Account(customerName); branchAccount[branchItems].Deposit(initDeposit); ++branchItems; } else throw new ApplicationException("Sorry " + name + " cannot accept any more accounts!"); } /// <summary> /// Return the Account by position in the collection. Assumes at least one. /// </summary> /// <param name="index">assumed 0 .. (getNumberOfAccounts() - 1)</param> public Account this[int index] { get { return branchAccount[index]; } } public String Name { get { return name; } } public int Count { get { return branchItems }; } /// <summary> /// Find the Account with Maximum Balance. Assumes at least one. /// </summary> /// <returns>Returns the account with the largest balance</returns> /// <exception cref="System.InvalidOperationException">Thrown if there /// are no accounts in the branch.</exception> public Account searchMaximum() { if(Count <= 0) throw new InvalidOperationException("There are no accounts in this branch"); Account maxAcc = this[0]; for (int i = 1 ; i < Count; i++) { if (this[i].Balance > maxAcc.Balance) { maxAcc = this[i]; } } return maxAcc; } }