Several common software naming rules

Source: Internet
Author: User

You don't have to work overtime today. Come back to watch movies and listen to songs. A long-planned blog has finally ushered in the first meaningful article today. I have read some articles on the Internet, but I am not writing well. I will try again.

In fact, there are many naming rules, which can be clearly understood. Here we will briefly introduce three naming rules: Hungary, Pascal, and camel:

 

I. Hungary naming convention: It is widely used in environments like Microsoft Windows.

A few years ago, Charles Simonyi (who later became a well-known programmer at Microsoft) designed a post-fix-based naming method known as "Hungary notation" to remember him. his idea is to give each identifier a prefix based on its meaning. microsoft later adopted this idea to give each identifier a prefix to describe its data type. therefore, the prefix of the integer variable is N, the long integer variable is NL, the numeric array variable is ca, and the string (character array ending with an empty type) is prefixed with Sz. these names may be odd. for example, lpszfoo indicates that "foo" is a long integer pointer to a string ending with an empty character. the advantage of this method is that you can identify the type of a variable by its name, instead of looking for its definition. unfortunately, this method not only bypasses the variable name, but also makes it very difficult to change the variable type. in windows3.1, the integer variable is 16 in width. if we use an integer variable at the beginning, but after using the 30---40 function, we find that the width of the integer variable is insufficient. Only the type of the variable needs to be changed, and the name of the variable in the 30--40 functions needs to be changed. because it is impractical, no one except some stubborn windows programmers can use "Hungary notation. there is no doubt that it still exists on some occasions, but most people have abandoned it now. generally, the input prefix is a bad idea because it binds the variable together with its type. the Hungary method is generally advantageous for functions with less than 30 rows. Especially for interface programming, it has advantages. However, with strong algorithm requirements, especially many abstract C ++ programs, the Hungarian method is a disaster. See where you are using it. Now we have good ide tools, such as Vc and sourceinsight. when you select a variable, the system will automatically prompt you for its declaration and definition, so that the Hungarian naming method is not necessary. this is nothing more than for better program readability. in fact, good code writing habits are more important than forcing the Hungarian naming method. systematic. Integrity. Readability. The classification should be clear. Annotations are required! The Hungarian naming convention is a naming convention promoted by Microsoft for various types of symbols such as variables, functions, objects, prefixes, and macro definitions. The main idea of the Hungarian naming method is to add prefixes to variables and function names to enhance people's understanding of programs. It was launched by a Hungary inside Microsoft. As a result, it gradually became popular within Microsoft and spread to Windows developers around the world. The following describes the Hungarian naming method, which will be followed by the above Code style as much as possible in the subsequent examples. In other words, not all readers are required to abide by the rules, but readers are expected to follow the rules as a modern software developer.

The Hungarian naming method identifies the scope and type of the variable by adding the symbol of the corresponding lowercase letter before the variable name as the prefix. These symbols can be used at multiple times. The sequence is first M _ (member variable), then pointer, then simple data type, and then others. For example, m_lpszstr indicates a long pointer member variable pointing to a string ending with 0 characters.

The key to the Hungarian naming method is that the identifier name starts with one or more lower-case letters as the prefix. The prefix is followed by one or more words in the upper-case letters, this word indicates the purpose of the variable.

The prefix of frequently used lowercase letters in the Hungarian naming method:

Prefix type
Array)
B Boolean)
Byte)
C signed character (char)
CB unsigned characters (char byte, not many people)
Cr color reference value (colorref)
CX, Cy Coordinate Difference (length shortint)
DW double word
FN Function
H handle (handle)
I integer
L long integer (long INT)
LP long pointer
M _ class member
N short INTEGER (short INT)
NP near pointer
P pointer
S string type
String type ending with null in SZ (string with zero end)
W word

Ii. Camel)

The camel command method, as its name indicates, refers to the combination of uppercase and lowercase letters to form the names of variables and functions. Note that the first word is always lowercase, the first letter of a word is in upper case, and the rest is in lower case. For example, the following is the same function named by the camel naming method and the underline method respectively:

Printemployeepaychecks ();

Print_employee_paychecks ();

The first function name uses the camel naming method-each logical breakpoint in the function name is marked with an uppercase letter; the second function name uses the underline method-each logical breakpoint in the function name is marked with an underscore.

The camel naming method has become increasingly popular in recent years.
In an environment like Windows, it is widely used. On the other hand, the underline method became popular after the emergence of C. It is widely used in many old programs and UNIX environments.

 

The benefits are obvious. You can clearly understand the meaning of naming, which is also a basic starting point for programming naming.

 

Iii. Pascal naming:

Similar to the camel naming method. However, the trigger name is the first letter in lower case, while the Pascal name is the first letter in upper case.

For example, public void
Displayinfo ();

String username;

Both use the Pascal naming method.

In C #, Pascal naming and camel naming are mostly used.

 

 

To sum up the situations in which they are used:

 

 

1 Hungary naming: an old Naming Convention that can be used in small functions with a low amount of code. Modern ide tools are not required. But programmers should be familiar with it.

 

2 camel name: it can be used more often. The main usage is C # reference:It is mainly used for variable naming rules, function parameters, variables,

 

3 Pascal name: Same as above, mainly used in type, function name, file name,

 

 

Attached the Chinese version of. Net naming convention

Word Selection

AvoidUse the type name replicated by the frequently used namespace. Type names cannot use the following words.
System collections forms UI

AvoidUse the identifier that conflicts with common keywords. For example, avoid using the following words.

Addhandler Addressof Alias And ANSI
As Assembly Auto Bitand Bitnot
Bitor Bitxor Boolean Byref Byte
Byval Call Case Catch Cbool
Cbyte Cchar Cdate Cdec Cdbl
Char CINT Class Clng Cobj
Const Cshort Csng CSTR Ctype
Date Decimal Declare Default Delegate
Dim Do Double Each Else
Elseif End Enum Erase Error
Event Exit Externalsource False Finally
For Friend Function Get GetType
Goto Handles If Implements Imports
In Inherits Integer Interface Is
Let Lib Like Long Loop
Me MoD Module Mustinherit Mustoverride
Mybase Myclass Namespace New Next
Not Nothing Notinheritable Notoverridable Object
On Option Optional Or Overloads
Overridable Overrides Paramarray Preserve Private
Property Protected Public Raiseevent Readonly
Redim Region Rem Removehandler Resume
Return Select Set Shadows Shared
Short Single Static Step Stop
String Structure Sub Synclock Then
Throw To True Try Typeof
Unicode Until Variant When While
With Withevents Writeonly XOR Eval
Extends Instanceof Package VaR

Identifier (including parameter name)NoUse the abbreviation.
If you must use the abbreviation:
All abbreviations with more than two characters use the camel capital format, even if this is not the standard abbreviation.

Namespace
The naming rules for namespaces are as follows:
CompanyName. policyname

In this way, the namespace we see should be like this:
Microsoft. Office
Powersoft. PowerBuilder

Note: This is just a principle. Third-party companies can select other names.

Avoid using the company name or the name of another famous brand as the prefix of the namespace, which may lead to the possibility that two published namespaces have the same name. (For example, name the Microsoft Office Automatic class Microsoft. Office .)

Use Pascal in upper case and use commas to separate logical components (for example, Microsoft. Office. PowerPoint ). If your brand uses a non-traditional capital mode, you must follow the capital mode determined by your brand, even if this method deviates from the usual namespace capital rules (for example, next. webobjects, and EE. cummings .)

The name of the complex namespace must be used when the complex number is used. For example, use system. Collections instead of system. collection. The special case of this rule is the brand name and abbreviation. For example, use system. Io instead of system. IOS.

The same name cannot be used for namespaces and classes. For example, after a class is named debug, do not use DEBUG as a namespace name.

Class and Class Composition

Class naming principles
Use a noun or a noun phrase to name a class.
Use Pascal in uppercase.
Reduce the usage of abbreviations in the class name.
Do not use any class prefix (such as C ).
Do not use underlined characters.

The following is an example of a correctly named class name.
Public classFilestream{
}
Public classButton{

}
Public classString{
}

Interface naming principles
Use a noun or noun phrase, or an adjective describing a behavior to name an interface. For example, icomponent, icustomattributeprovider, and ipersistable ).
Use Pascal in uppercase.
Reduce the usage of the abbreviation in the interface name.
Do not use underlined characters.
Add the prefix I before the interface name to indicate that this type is an interface.
Do not add the prefix C before the class name. In other cases, I must be added before the class name without indicating that it is an interface. In this case, only the characters after I are lowercase (for example, identitystore .)
When a class is the standard execution of an interface, similar names are used to define this pair of classes/interfaces. The difference between the two names is that the interface name has an I prefix before it.

The following is an example of the icomponent interface and its standard execution Class component.
Public interfaceIcomponent{
}
Public Class component:Icomponent{
}
Public interfaceIserviceprovider{
}
Public interfaceIformatable{
}

Attribute naming principles

Add the attribute suffix after the attribute to customize the attribute class. As shown in the following example.
Public classObsoleteattribute{
}

EnumNaming principles
Use Pascal in upper case for enum.
The enum value name must be in the upper case of Pascal.
Reduce the usage of the abbreviation in The enum name.
Do not add a prefix before the enum name (for example, adxxx indicates ADO enums, rtfxxx indicates multi-information text Enum, and so on .).
Do not add an Enum suffix to The enum type.
The enum name must be a singular noun.
The bit field uses plural nouns.
If the enumerated value is used in a parameter or attribute, an Enum is required to define the enumerated value. In this way, the tool can know the possible values of an attribute or parameter.

Public Enum filemode {
Create,
Createnew,
Open,
Openorcreate,
Truncate
}

If the numeric value is to be bitwise OR 'ed together, use flags to customize the attribute.

[Flags]
Public Enum bindings {
Createinstance,
Defaultbinding,
Excatbinding,
Getfield,
Getproperty,
Ignorecase,
Invokemethod,
Nonpublic,
Oabinding,
Setfield
Setproperty,
Static
}

When encapsulating a Win32 API, this rule has a special case. It is common to generate an internal definition from a Win32 header. You can use Win32 uppercase letters, which are usually all uppercase letters.

Use int32 as the basic type of an enum.
If this Enum represents a flag and there are many signs (greater than 32), or this Enum can be expanded to many signs in the future, or the type needs to be different from the type int for backward compatibility, in this case, a special case is generated.

Enum is used only when the value can be fully expressed as a set of bits. You cannot use Enum (for example, the operating system version) for an open set ).

Read-only andConstField name
Use nouns, noun phrases, or abbreviations to name static fields.
Use Pascal to name static fields in uppercase.
Do not use Hungarian symbols as the prefix of static field names.

Parameter Name
Use descriptive parameter names. The parameter name should be descriptive, so that in most cases, the parameter name and its type can be used to determine its meaning.
Name parameters in upper case of camel.
Name a parameter based on its meaning, rather than based on its type. We hope that the development tool can provide information about the parameter types in a convenient way, so that the parameter name can be used better, And the semantics rather than the type can be described. However, it is only possible to use a parameter name based on the type.

Do not use reserved parameters. You can add more data in the next version.
Do not use a Hungarian symbol as the prefix of the field name.

Type GetType (stringTypename)
String format (stringFormat, Object []ARGs)

Method naming principles
Use the verb or verb phrase naming method.
Use the Pascal capital naming method shown in the following example.
Removeall ()
Getchararray ()
Invoke ()

Attribute naming principles
Use nouns or phrases to name attributes.
Use Pascal to name attributes in uppercase.
The property and type must be the same.
When you name an attribute with the same name as a type, the type of this attribute becomes that type. Although it sounds strange, this is correct. The following example correctly uses the attribute naming principle.
Public Enum color {...}
Public class control {
Public color {get {...} set {...}}
}
The following example is incorrect.
Public Enum color {...}
Public class control {
Public int color {get {...} set {...}}
}

In that incorrect example, it is impossible to reference color Enum because color and XXX will be translated into a member for access, it will first obtain the value of the color attribute (INT type), and then access the member of that value (it should be system. an instance Member of int32 ).

Event naming principles
Use the eventhandloer suffix to name the event handler, as shown in the following figure.
Public Delegate voidMouseeventhandler(Object sender, mouseevent E );

Use the sender and e parameters.
The sender parameter represents the object of the proposed event. The sender parameter is always a type object, even if it may use a more specific type.

Event-related states are encapsulated in an event class example named E. Use the correct and specific event classes of this type.
Public Delegate void mouseeventhandler (ObjectSender, MouseeventE);

Use the eventargs suffix to name the event independent variable class, as shown in the following example.
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 ;}}
}

When naming an event name, you must have the concepts of the past tense and the later tense. Therefore, you must use the current tense and the past tense (do not use the beforexxx/afterxxx method ). For example, a closed event that can be canceled includes a closing event and a closed event.

Public event controleventhandler controladded {
//..
}

Name an event with a verb.

Case Sensitive
Do not use names that need to be case sensitive. Each component must be fully available in both case-sensitive and case-insensitive languages. Because case-insensitive languages cannot differentiate only two names with different cases in the same environment, this situation must be avoided.
Do not generate two namespaces with the same name and only case-insensitive.
Namespace ee. Cummings;
Namespace ee. Cummings;
It has a type of two parameters. The names of the two parameters must not be case-insensitive.
Void Foo (string a, string)
System. winforms. point P;
System. winforms. Point pp;
A type with two attributes. The attribute names must be case-insensitive.
Int Foo {Get, set };
Int Foo {Get, set}
The method name must be case-insensitive.
Void Foo ();
Void Foo ();

Avoid confusion of type names

Different languages use different terms to identify basic management types. Designers must avoid the use of language-specific terms. Follow the rules described in this chapter to avoid confusion of type names.
Use a semantic name instead of a type name.
In rare cases, except for the type, the parameter has no meaning in semantics. In this case, the class name is used. For example, if a class supports writing multiple data types into a stream, this class may have the following methods:
Void write (double value );
Void write (float value );
Void write (long value );
Void write (INT value );
Void write (short value );
The above example is the first choice when the following has special requirements on languages.
Void write (double doublevalue );
Void write (float floatvalue );

Void write (long longvalue );
Void write (INT intvalue );
Void write (short writable value );

In extreme cases, each basic data type requires a unique naming method, and the following generic type name is used.

C # type name Visual Basic type name JScript type name Visual c ++ type name Il Representation Universal type name
Sbyte Sbyte Sbyte Char I1 Sbyte
Byte Byte Byte Unsigned char U1 Byte
Short Short Short Short I2 Int16
Ushort Uint16 Uint16 Unsigned short U2 Uint16
Int Integer Int Int I4 Int32
Uint Na Na Unsigned int U4 Uint32
Long Long Long _ Int64 I8 Int64
Ulong Uint64 Uint64 Unsigned _ int64 U8 Uint64
Float Single Float Float R4 Single
Double Double Double Double R8 Double
Bool Boolean Boolean Bool I4 Boolean
Char Char Char Wchar_t U2 Char
String String String String System. String String
Object Object Object Object System. Object Object

You can use the following methods to read multiple data types from a stream.
Double readdouble ();
Float readsingle ();
Long readin64 ();
Int readint32 ();
Short readint16 ();

The above example is the first choice when the following has special requirements on languages.
Double readdouble ();
Float readfloat ();
Long readlong ();
Int readint ();
Short readshort ();

 

 

 

 

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.