Home Random Page


CATEGORIES:

BiologyChemistryConstructionCultureEcologyEconomyElectronicsFinanceGeographyHistoryInformaticsLawMathematicsMechanicsMedicineOtherPedagogyPhilosophyPhysicsPolicyPsychologySociologySportTourism






Indentation, spaces and braces

Introduction

Overview

This document presents .NET version of coding guidelines that is obligatory for all Itransition software development process.

Scope of the document

All details about development for other platforms are placed in separate documents. Platform independent information (like scripts development, graphical resources development) is stored in separate document.

This document contains information regarding to C# language mainly, however special section describes points significant to Visual Basic .NET.

Targeted readers

Targeted readers for the document are all Itransition .NET developers.

Typographical conventions

The following special typographical conventions are used within the document:

Font Description
Italic Represents emphasis or a referenced material’s title.
Fixed width Represents any source code fragments (like class, method or attribute names), file names, etc.

Naming conventions

Introduction

A consistent naming pattern is one of the most important elements of predictability and discoverability in a managed source code. Widespread use and understanding of these naming guidelines should eliminate many of the most common user questions. This section provides naming guidelines for the different types of entities used.

All identifiers should be written using only proper English words. Avoid too sophisticated words. Do not misuse words. Try to find the simplest and most correct word. Usually you should write “Unique”, but not “Extraordinary”.

The major goal of all conventions is high level of code understandability and maintainability. If you feel that conventions violation can increase understandability in some particular case, you can do that. But think twice before.

You might also have to violate these guidelines to maintain compatibility with existing code. For example, uppercase characters are often used for enumerations and constant values in unmanaged code. In general, these symbols should not be visible outside of the class/assembly that uses them.

Do not use language specific naming. Do not create language-specific method and parameters names, as in the following example:

void Write(double doubleValue);

void WriteDouble(double value);

Use instead:

void Write(double value);

In the extremely rare case when it is necessary to create a uniquely named method for each fundamental data type, use a universal type name (use ReadInt16() instead of ReadShort()).

It is recommended not to replace System.Object (and System.String) type by object keyword (string correspondingly). It is better to use “Object” (“String”), not as “object” (“string”) to emphasize its object nature.

Avoid using names that duplicate commonly used .NET Framework namespaces and classes. For example, do not use any of the following names as a class name: System, Collections, Forms, or UI. See the Class Library in the MSDN for a list of .NET Framework namespaces.



In addition, avoid using identifiers that conflict with the keywords listed in the Word Choice MSDN article.

Abbreviations

To avoid confusion and guarantee cross-language interoperation, follow these rules regarding the use of abbreviations:

Ø Do not use abbreviations or contractions as parts of identifier names. This rule strictly selects InternetAddress spelling instead of InetAddress, InternetAddr, InetAddr. This significantly simplifies development, code analysis and maintenance.

Ø Do not use acronyms that are not generally accepted in the computing field at all. If well-known acronym exists use it to replace lengthy phrase names. For example: XML, HTML, HTTP, FTP, DB, IO, and UI. Also some widespread file extensions can be used (for example, PDF, GIF, JPEG, BMP, TIFF). However avoid problem area specific acronyms like DM; use DocumentManagement instead.

Ø When using acronyms, use Pascal case or camel case for acronyms more than two characters long. For example, use HtmlButton or htmlButton. However, you should capitalize acronyms that consist of only two characters, such as System.IO instead of System.Io.

Ø Do not use a Hungarian notation prefix anywhere.

Case sensitivity

To avoid confusion and guarantee cross-language interoperation, follow these rules regarding the use of case sensitivity:

Ø Do not use names that require case sensitivity. Components must be fully usable from both case-sensitive and case-insensitive languages. Case-insensitive languages cannot distinguish between two names within the same context that differ only by case. Therefore, you must avoid this situation in the components or classes that you create.

Ø Do not create two namespaces with names that differ only by case. For example, a case insensitive language cannot distinguish between the following two namespace declarations:

namespace ee.cummings;

namespace Ee.Cummings;

Ø Do not create a function with parameter names that differ only by case. The following example is incorrect:

void MyFunction(string a, string A)

Ø Do not create a namespace with type names that differ only by case. In the following example, Point p and POINT p are inappropriate type names because they differ only by case:

System.Windows.Forms.Point p

System.Windows.Forms.POINT p

Ø Do not create a type with property names that differ only by case. In the following example, int Color and int COLOR are inappropriate property names because they differ only by case:

int Color

int COLOR

Ø Do not create a type with method names that differ only by case. In the following example, calculate and Calculate are inappropriate method names because they differ only by case:

void calculate()

void Calculate()

Namespaces

The general rule for naming namespaces is to use the company name followed by the project name and optionally the feature or module name (which can be followed by sub-feature or sub-module name):

CompanyName.Project[.Module][.SubModule]

For example (code belonged to Itransition):

Itransition.Framework

Itransition.Framework.Web

Itransition.Framework.Web.Controls

Or for offshore code:

Cimage.Fusion

Cimage.Fusion.WebClient

Genesys.Voodoo

Genesys.Voodoo.Common

Name a namespace that contains types that provide design-time functionality for a base namespace with the .Design suffix.

Usually, a nested namespace should have a dependency on types in the containing namespace. For example, the classes in the System.Web.UI.Design depend on the classes in System.Web.UI. However, the classes in System.Web.UI do not depend on the classes in System.Web.UI.Design.

You should use Pascal case for namespaces, and separate logical components with periods, as in Microsoft.Office.PowerPoint. If your brand employs nontraditional casing, follow the casing defined by your brand, even if it deviates from the prescribed Pascal case. For example, the namespaces NeXT.WebObjects and ee.cummings illustrate appropriate deviations from the Pascal case rule.

Use plural namespace names if it is semantically appropriate. For example, use System.Collections rather than System.Collection. Exceptions to this rule are brand names and abbreviations. For example, use System.IO rather than System.IOs.

Do not use the same name for a namespace and a class. For example, do not provide both a Debug namespace and a Debug class.

If you develop several assemblies for the project it is recommended to use “main” namespace name as assembly name. For example, assembly Microsoft.SharePoint.dll contains Microsoft.SharePoint, Microsoft.SharePoint.WebControls, Microsoft.SharePoint.WebPartPages, etc. namespaces.

Classes

The following rules outline the guidelines for naming classes:

Ø Use a noun or noun phrase to name a class.

Ø Use Pascal case.

Ø Do not use a type prefix, such as C for class, on a class name. For example, use the class name FileStream rather than CFileStream.

Ø Do not use the underscore character (_).

Ø Occasionally, it is necessary to provide a class name that begins with the letter I, even though the class is not an interface. This is appropriate as long as I is the first letter of an entire word that is a part of the class name. For example, the class name IdentityStore is appropriate.

Ø Exception class name should always be suffixed with “Exception”.

Ø Where appropriate, use a compound word to name a derived class. The second part of the derived class's name should be the name of the base class. For example, ApplicationException is an appropriate name for a class derived from a class named Exception, because ApplicationException is a kind of Exception. Use reasonable judgment in applying this rule. For example, Button is an appropriate name for a class derived from Control. Although a button is a kind of control, making Control a part of the class name would lengthen the name unnecessarily.

For example:

Sign

VerifiableStream

ExternalContractException

TransformationMatrix

Interfaces

The following rules outline the naming guidelines for interfaces:

Ø Name interfaces with nouns or noun phrases, or adjectives that describe behavior. For example, the interface name IComponent uses a descriptive noun. The interface name ICustomAttributeProvider uses a noun phrase. The name IPersistable uses an adjective.

Ø Use Pascal case.

Ø Prefix interface names with the letter I, to indicate that the type is an interface.

Ø Use similar names when you define a class/interface pair where the class is a standard implementation of the interface. The names should differ only by the letter I prefix on the interface name (for example, ITreeModel and TreeModel). To name abstract class that partially implements interface I<Name> use Abstract<Name> identifier (for example, ITreeModel and AbstractTreeModel).

Ø Do not use the underscore character (_).

The following are examples of correctly named interfaces:

ITableModel

IVerifiable

Attributes

You should always add the suffix Attribute to custom attribute classes. The following is an example of a correctly named attribute class:

HistoryAttribute

Exceptions

You should always add the suffix Exception to custom exception classes. The following is an example of a correctly named exception class:

ExternalContractException

Enumerations

The following rules outline the naming guidelines for enumerations:

Ø Use Pascal case for Enum types and value names.

Ø Do not use an Enum suffix on Enum type names.

Ø Use a singular name for most Enum types, but use a plural name for Enum types that are bit fields (flags).

Ø Always add the FlagsAttribute to a bit field Enum type.

Example:

ActionType

NavigationOptions

Static fields

The following rules outline the naming guidelines for static fields:

Ø Use nouns, noun phrases, or abbreviations of nouns to name static fields.

Ø Use Pascal case.

Ø It is recommended to use static properties instead of public static fields whenever possible.

Ø Give Current name to the static property for class instance.

Parameters

The following rules outline the naming guidelines for parameters:

Ø Use camel case for parameter names.

Ø Use descriptive parameter names. Parameter names should be descriptive enough so that the name of the parameter and its type can be used to determine its meaning in most scenarios. For example, visual design tools that provide context sensitive help display method parameters to the developer as they type. The parameter names should be descriptive enough in this scenario to allow the developer to supply the correct parameters.

Ø Use names that describe a parameter's meaning rather than names that describe a parameter's type. Development tools should provide meaningful information about a parameter's type. Therefore, a parameter's name can be put to better use by describing meaning. Use type-based parameter names sparingly and only where it is appropriate.

Ø Do not use reserved parameters. Reserved parameters are private parameters that might be exposed in a future version if they are needed. Instead, if more data is needed in a future version of your class library, add a new overload for a method.

The following are examples of correctly named parameters:

Process(int priority, Object[] arguments)

Methods

The following rules outline the naming guidelines for methods:

Ø Use verbs or verb phrases to name methods.

Ø Use Pascal case.

Ø Do not add information about parameter types in method name (use overloading instead).

The following are examples of correctly named methods.

RemoveAll()

ProcessCharArray()

Invoke()

Properties

The following rules outline the naming guidelines for properties:

Ø Use a noun or noun phrase to name properties.

Ø Use Pascal case.

For example:

ParentElement

Current

Next

Events

The following rules outline the naming guidelines for events:

Ø Use Pascal case.

Ø Use an EventHandler suffix on event handler names.

Ø Specify two parameters named sender and e. The sender parameter represents the object that raised the event. The sender parameter is always of type System.Object, even if it is possible to use a more specific type. The state associated with the event is encapsulated in an instance of an event class named e. Use an appropriate and specific event class for the e parameter type.

Ø Name an event argument class with the EventArgs suffix.

Ø Consider naming events with a verb. For example, correctly named event names include Clicked, Painting, and DroppedDown.

Ø Use a gerund (the "ing" form of a verb) to create an event name that expresses the concept of pre-event, and a past-tense verb to represent post-event. For example, a close event that can be canceled should have a Closing event and a Closed event. Do not use the BeforeXxx/AfterXxx naming pattern.

Ø Do not use a prefix or suffix on the event declaration on the type. For example, use Close instead of OnClose.

Ø In general, you should provide a protected method called OnXxx on types with events that can be overridden in a derived class. This method should only have the event parameter e, because the sender is always the instance of the type.

The following example illustrates an event handler with an appropriate name and parameters:

delegate void MouseEventHandler(object sender, MouseEventArgs e);

The following example illustrates a correctly named event argument class:

public class MouseEventArgs : EventArgs

{

int x;

int y;

 

public MouseEventArgs(int x, int y)

{

this.x = x;

this.y = y;

}

 

public int X

{

get

{

return x;

}

}

 

public int Y

{

get

{

return y;

}

}

}

Local variables

The following rules outline the naming guidelines for local variables:

Ø Use camel case for parameter names.

Ø Use descriptive parameter names. However, in for cycle, it is possible to use System.Int32 variable with name i (and j, if necessary).

Ø Avoid unnecessary abbreviations.

For example,

int accumulator;

String result;

double spin = 0.5;

for (int i = 0; i < size; i++) { … }

Type parameters

The following rules outline the naming guidelines for type parameters:

Ø Use Pascal case.

Ø Do name generic type parameters with descriptive names, unless a single letter name is completely self-explanatory and a descriptive name would not add value.

Ø Consider using T as the type parameter name for types with one single letter type parameter.

Ø Do prefix descriptive type parameter names with “T”.

Ø Consider indicating constraints placed on a type parameter in the name of parameter. For example, a parameter constrained to ISession may be called TSession.

For example,

public interface ISessionChannel<TSession> { … }

public delegate TOutput Converter<TInput, TOutput>(TInput from);

public class List<T> { … }

Summary

Identifier Case Example
Class Pascal Application
Enum Pascal ErrorLevel
Enum value Pascal FatalError
Event Pascal ValueChange
Exception class Pascal WebException (always ends with Exception)
Attribute class Pascal VersionAttribute (always ends with Attribute)
Interface Pascal IDisposable (always starts with I)
Method Pascal ToString
Namespace Pascal System
Parameter Camel typeName
Property Pascal BackColor
Private field Camel redValue
Non-private field Pascal RedValue
Local variable Camel accountType
Type parameter Pascal TSession

Comments

Introduction

All source code documenting inside source files has to follow C# language specification (“Documentation comments” appendix). Specific additions are described in the following sub-sections.

Class comments

Although it’s recommended to provide enough details on each source code part (method, class, etc) in accordance with C# language specification, at least class <summary> section is absolutely mandatory. No file should be delivered without this part of source code documentation.

Method comments

All public and protected methods should have detailed documentation. <summary> section is absolutely mandatory. If method throws non-trivial exceptions they should be documented (for example, NullReferenceException in case of passing null parameter may not be documented). Parameters and return value should be documented if method is complex or its name is not enough understandable.

Inline comments

Non-trivial code should be obligatory documented. It relates to: algorithms (for example, fast Fourier transform), not documented features usage, some non-trivial optimizations, etc.

It may be convenient to place specific comments indicating that some source code is not finalized yet and still require further changes or improvements. In the same time, intermediate source code versions may be released prior to such “finalization”. In that case, the following way should be used to declare intention of applying some modifications to that part of source code in the future:

// TODO: <Details of planned modification/improvement>

This comment should be placed either just before target source code part or at the end of the first line of target source code part.

Example:

// TODO: Use caching mechanism here.

Service service = GetService();

Code formatting

Files and folders

Place every top-level type in the separate file (whether type public or note). Folder structure should correspond to the namespaces.

For example, class Itransition.Framework.Collections.RandomList should be placed in the “…/Itransition/Framework/Collections/RandomList.cs” file.

Indentation, spaces and braces

The following rules outline the formatting guidelines for indentation and braces:

Ø Indentation should be 4 space characters (tabs usage is prohibited).

Ø Braces should not reside on the same line as related construct.

Ø Case labels should use indentation.

Ø All flow control primitives (if, else, while, for, do, switch) shall be followed by braces, even if they have single operation.

Ø Methods, properties, fields, events and nested types should be separated by single empty line. Related fields can be placed on the sequential lines however.

Ø When instruction spares several lines, second and subsequent ones should be indented with 4 space characters.

Ø If necessary, method logic can contain empty lines if it increases understandability (however, small methods strongly encouraged).

For example:

public class Point : EventArgs

{

double x;

double y;

 

public Point(double x, double y)

{

this.x = x;

this.y = y;

}

 

public double X

{

get

{

return x;

}

}

 

public int Y

{

get

{

double y;

}

}

 

public PointType GetType()

{

double radius = x * x + y * y;

if(Math.Abs(radius – 1.0) < 0.000001)

{

return PointType.Periodic;

}

if(radius < 1.0)

{

return PointType.Converging;

}

else

{

return PointType.Divergent;

}

}

}


Date: 2015-12-24; view: 648


<== previous page | next page ==>
L’histoire comme roman du possible, le roman comme possible de l’histoire | Separation of operators and punctuators
doclecture.net - lectures - 2014-2024 year. Copyright infringement or personal data (0.024 sec.)