Thursday, June 14, 2012

Naming Guidelines


A consistent naming pattern is one of the most important elements of predictability and discoverability in a managed class library. Widespread use and understanding of these naming guidelines should eliminate many of the most common user questions. This topic provides naming guidelines for the .NET Framework types. For each type, you should also take note of some general rules with respect to capitalization styles, case sensitivity and word choice.

In This Section

Capitalization Styles

Describes the Pascal case, camel case, and uppercase capitalization styles to use to name identifiers in class libraries.

1Use the following three conventions for capitalizing identifiers.

Pascal case
The first letter in the identifier and the first letter of each subsequent concatenated word are capitalized. You can use Pascal case for identifiers of three or more characters. For example:
BackColor
Camel case
The first letter of an identifier is lowercase and the first letter of each subsequent concatenated word is capitalized. For example:
backColor
Uppercase
All letters in the identifier are capitalized. Use this convention only for identifiers that consist of two or fewer letters. For example:
System.IO
System.Web.UI
You might also have to capitalize identifiers to maintain compatibility with existing, unmanaged symbol schemes, where all uppercase characters are often used for enumerations and constant values. In general, these symbols should not be visible outside of the assembly that uses them.
The following table summarizes the capitalization rules and provides examples for the different types of identifiers.
IdentifierCaseExample
ClassPascalAppDomain
Enum typePascalErrorLevel
Enum valuesPascalFatalError
EventPascalValueChange
Exception classPascalWebException
Note   Always ends with the suffix Exception.
Read-only Static fieldPascalRedValue
InterfacePascalIDisposable
Note   Always begins with the prefix I.
MethodPascalToString
NamespacePascalSystem.Drawing
ParameterCameltypeName
PropertyPascalBackColor
Protected instance fieldCamelredValue
Note   Rarely used. A property is preferable to using a protected instance field.
Public instance fieldPascalRedValue
Note   Rarely used. A property is preferable to using a public instance field.

Case Sensitivity

Describes the case sensitivity guidelines to follow when naming identifiers in class libraries.
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 andPOINT 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 {get, set}
    int COLOR {get, set}
    
  • Do not create a type with method names that differ only by case. In the following example, calculate andCalculate are inappropriate method names because they differ only by case.
    void calculate()
    void Calculate()

Abbreviations

Describes the guidelines for using abbreviations in type names.
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. For example, use GetWindow instead ofGetWin.
  • Do not use acronyms that are not generally accepted in the computing field.
  • Where appropriate, use well-known acronyms to replace lengthy phrase names. For example, use UI for User Interface and OLAP for On-line Analytical Processing.
  • 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 asSystem.IO instead of System.Io.
  • Do not use abbreviations in identifiers or parameter names. If you must use abbreviations, use camel case for abbreviations that consist of more than two characters, even if this contradicts the standard abbreviation of the word.

Word Choice

Lists the keywords to avoid using in type names.
Avoid using class names that duplicate commonly used .NET Framework namespaces. For example, do not use any of the following names as a class name: SystemCollectionsForms, or UI. See the Class Library for a list of .NET Framework namespaces.
In addition, avoid using identifiers that conflict with the following keywords.
AddHandlerAddressOfAliasAndAnsi
AsAssemblyAutoBaseBoolean
ByRefByteByValCallCase
CatchCBoolCByteCCharCDate
CDecCDblCharCIntClass
CLngCObjConstCShortCSng
CStrCTypeDateDecimalDeclare
DefaultDelegateDimDoDouble
EachElseElseIfEndEnum
EraseErrorEventExitExternalSource
FalseFinalizeFinallyFloatFor
FriendFunctionGetGetTypeGoto
HandlesIfImplementsImportsIn
InheritsIntegerInterfaceIsLet
LibLikeLongLoopMe
ModModuleMustInheritMustOverrideMyBase
MyClassNamespaceNewNextNot
NothingNotInheritableNotOverridableObjectOn
OptionOptionalOrOverloadsOverridable
OverridesParamArrayPreservePrivateProperty
ProtectedPublicRaiseEventReadOnlyReDim
RegionREMRemoveHandlerResumeReturn
SelectSetShadowsSharedShort
SingleStaticStepStopString
StructureSubSyncLockThenThrow
ToTrueTryTypeOfUnicode
UntilvolatileWhenWhileWith
WithEventsWriteOnlyXorevalextends
instanceofpackagevar

Avoiding Type Name Confusion

Describes how to avoid using language-specific terminology in order to avoid type name confusion.
Different programming languages use different terms to identify the fundamental managed types. Class library designers must avoid using language-specific terminology. Follow the rules described in this section to avoid type name confusion.
Use names that describe a type's meaning rather than names that describe the type. In the rare case that a parameter has no semantic meaning beyond its type, use a generic name. For example, a class that supports writing a variety of data types into a stream might have the following methods.
Sub Write(value As Double);
Sub Write(value As Single);
Sub Write(value As Long);
Sub Write(value As Integer);
Sub Write(value As Short);
[C#]
void Write(double value);
void Write(float value);
void Write(long value);
void Write(int value);
void Write(short value);
Do not create language-specific method names, as in the following example.
Sub Write(doubleValue As Double);
Sub Write(singleValue As Single);
Sub Write(longValue As Long);
Sub Write(integerValue As Integer);
Sub Write(shortValue As Short);
[C#]
void Write(double doubleValue);
void Write(float floatValue);
void Write(long longValue);
void Write(int intValue);
void Write(short shortValue);
In the extremely rare case that it is necessary to create a uniquely named method for each fundamental data type, use a universal type name. The following table lists fundamental data type names and their universal substitutions.
C# type nameVisual Basic type nameJScript type nameVisual C++ type nameIlasm.exe representationUniversal type name
sbyteSBytesBytecharint8SByte
byteBytebyteunsigned charunsigned int8Byte
shortShortshortshortint16Int16
ushortUInt16ushortunsigned shortunsigned int16UInt16
intIntegerintintint32Int32
uintUInt32uintunsigned intunsigned int32UInt32
longLonglong__int64int64Int64
ulongUInt64ulongunsigned __int64unsigned int64UInt64
floatSinglefloatfloatfloat32Single
doubleDoubledoubledoublefloat64Double
boolBooleanbooleanboolboolBoolean
charCharcharwchar_tcharChar
stringStringstringStringstringString
objectObjectobjectObjectobjectObject
For example, a class that supports reading a variety of data types from a stream might have the following methods.
ReadDouble()As Double
ReadSingle()As Single
ReadInt64()As Long
ReadInt32()As Integer
ReadInt16()As Short
[C#]
double ReadDouble();
float ReadSingle();
long ReadInt64();
int ReadInt32();
short ReadInt16();
The preceding example is preferable to the following language-specific alternative.
ReadDouble()As Double
ReadSingle()As Single
ReadLong()As Long
ReadInteger()As Integer
ReadShort()As Short
[C#]
double ReadDouble();
float ReadFloat();
long ReadLong();
int ReadInt();
short ReadShort();

Namespace Naming Guidelines

Describes the guidelines to follow when naming namespaces.
The general rule for naming namespaces is to use the company name followed by the technology name and optionally the feature and design as follows.
CompanyName.TechnologyName[.Feature][.Design]
For example:
Microsoft.Media
Microsoft.Media.Design
Prefixing namespace names with a company name or other well-established brand avoids the possibility of two published namespaces having the same name. For example, Microsoft.Office is an appropriate prefix for the Office Automation Classes provided by Microsoft.
Use a stable, recognized technology name at the second level of a hierarchical name. Use organizational hierarchies as the basis for namespace hierarchies. Name a namespace that contains types that provide design-time functionality for a base namespace with the .Design suffix. For example, the System.Windows.Forms.Design Namespace contains designers and related classes used to design System.Windows.Forms based applications.
A nested namespace should have a dependency on types in the containing namespace. For example, the classes in theSystem.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 inMicrosoft.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.cummingsillustrate appropriate deviations from the Pascal case rule.
Use plural namespace names if it is semantically appropriate. For example, use System.Collections rather thanSystem.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 aDebug class.
Finally, note that a namespace name does not have to parallel an assembly name. For example, if you name an assembly MyCompany.MyTechnology.dll, it does not have to contain a MyCompany.MyTechnology namespace.

Class Naming Guidelines

Describes the guidelines to follow when naming classes.
The following rules outline the guidelines for naming classes:
  • Use a noun or noun phrase to name a class.
  • Use Pascal case.
  • Use abbreviations sparingly.
  • Do not use a type prefix, such as for class, on a class name. For example, use the class name FileStreamrather 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.
  • 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 fromControl. Although a button is a kind of control, making Control a part of the class name would lengthen the name unnecessarily.
The following are examples of correctly named classes.
Public Class FileStream
Public Class Button
Public Class String
[C#]
public class FileStream
public class Button
public class String

Interface Naming Guidelines

Describes the guidelines to follow when naming 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.
  • Use abbreviations sparingly.
  • 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.
  • Do not use the underscore character (_).
The following are examples of correctly named interfaces.
Public Interface IServiceProvider
Public Interface IFormatable
[C#]
public interface IServiceProvider
public interface IFormatable
The following code example illustrates how to define the interface IComponent and its standard implementation, the class Component.
Public Interface IComponent
   ' Implementation code goes here.
End Interface

Public Class Component
   Implements IComponent
   ' Implementation code goes here.
End Class

[C#]
public interface IComponent 
{
   // Implementation code goes here.
}
public class Component: IComponent 
{
   // Implementation code goes here.
}

Attribute Naming Guidelines

Describes the correct way to name an attribute using the Attribute suffix.
You should always add the suffix Attribute to custom attribute classes. The following is an example of a correctly named attribute class.
Public Class ObsoleteAttribute
[C#]
public class ObsoleteAttribute{}

Enumeration Type Naming Guidelines

Describes the guidelines to follow when naming enumerations.
The enumeration (Enum) value type inherits from the Enum Class. The following rules outline the naming guidelines for enumerations:
  • Use Pascal case for Enum types and value names.
  • Use abbreviations sparingly.
  • 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.
  • Always add the FlagsAttribute to a bit field Enum type.

Static Field Naming Guidelines

Describes the guidelines to follow when naming 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.
  • Do not use a Hungarian notation prefix on static field names.
  • It is recommended that you use static properties instead of public static fields whenever possible.

Parameter Naming Guidelines

Describes the guidelines to follow when naming parameters.
It is important to carefully follow these parameter naming guidelines because visual design tools that provide context sensitive help and class browsing functionality display method parameter names to users in the designer. 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 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.
  • Do not prefix parameter names with Hungarian type notation.
The following are examples of correctly named parameters.
GetType(typeName As String)As Type
Format(format As String, args() As object)As String
[C#]
Type GetType(string typeName)
string Format(string format, object[] args)

Method Naming Guidelines

Describes the guidelines to follow when naming methods.
The following rules outline the naming guidelines for methods:
  • Use verbs or verb phrases to name methods.
  • Use Pascal case.
The following are examples of correctly named methods.
RemoveAll()
GetCharArray()
Invoke()

Property Naming Guidelines

Describes the guidelines to follow when naming properties.
The following rules outline the naming guidelines for properties:
  • Use a noun or noun phrase to name properties.
  • Use Pascal case.
  • Do not use Hungarian notation.
  • Consider creating a property with the same name as its underlying type. For example, if you declare a property named Color, the type of the property should likewise be Color. See the example later in this topic.
The following code example illustrates correct property naming.
Public Class SampleClass 
   Public Property BackColor As Color
      ' Code for Get and Set accessors goes here.
   End Property
End Class
[C#]
public class SampleClass
{
   public Color BackColor 
   {
      // Code for Get and Set accessors goes here.
   }
}
The following code example illustrates providing a property with the same name as a type.
Public Enum Color 
   ' Insert code for Enum here. 
End Enum
Public Class Control 
   Public Property Color As Color
      Get
         ' Insert code here.
      End Get 
      Set
         ' Insert code here.
      End Set
   End Property
End Class
[C#]
public enum Color 
{
   // Insert code for Enum here.
}
public class Control 
{
   public Color Color 
   { 
      get {// Insert code here.} 
      set {// Insert code here.} 
   }
}
The following code example is incorrect because the property Color is of type Integer.
Public Enum Color 
   ' Insert code for Enum here. 
End Enum
Public Class Control 
   Public Property Color As Integer
      Get
         ' Insert code here.
      End Get 
      Set
         ' Insert code here.
      End Set
   End Property
End Class
[C#]
public enum Color {// Insert code for Enum here.}
public class Control 
{
   public int Color 
   { 
      get {// Insert code here.} 
      set {// Insert code here.}  
   }
}
In the incorrect example, it is not possible to refer to the members of the Color enumeration. Color.Xxx will be interpreted as accessing a member that first gets the value of the Color property (type Integer in Visual Basic or typeint in C#) and then accesses a member of that value (which would have to be an instance member of System.Int32).

Event Naming Guidelines

Describes the guidelines to follow when naming events.
The following rules outline the naming guidelines for events:
  • Use Pascal case.
  • Do not use Hungarian notation.
  • 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 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 ClickedPainting, andDroppedDown.
  • 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 Closingevent 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.
Public Delegate Sub MouseEventHandler(sender As Object, e As MouseEventArgs)
[C#]
public delegate void MouseEventHandler(object sender, MouseEventArgs e);
The following example illustrates a correctly named event argument class.
Public Class MouseEventArgs
   Inherits EventArgs 
   Dim x As Integer
   Dim y As Integer

   Public Sub New MouseEventArgs(x As Integer, y As Integer) 
      me.x = x
      me.y = y
   End Sub
      
   Public Property X As Integer
      Get 
         Return x
      End Get
   End Property
      
   Public Property Y As Integer
      Get 
         Return y
      End Get
   End Property
End Class
[C#]
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; } } 
}

No comments:

Post a Comment