命名规范
命名应尽量使用匈牙利命名法,变量名或函数名中使用大写字符来区分各个部分,以便于记忆和阅读。如bPatchMinute, DeleteDirInfo()。全局(包括类中的)变量用长名字,局部变量用短名字。
类成员变量前一般应加上m_,全局变量加上g_,仅与本模块有关的变量加上l_,紧接着是变量的类型。
整型: n,i
长整型: l
无符号整型: u
无符号长整型:dw
字符: ch
布尔量: b
浮点数: f
双精度浮点: d
字符串: str,lpsz,sz,p,lp,ac,
指针: p
字节指针: pb
无符号指针: pv
字符指针: lpsz
整型指针: lpn
文件指针: fp
如:
m_nTotalNum,m_strPath,m_bRcving,m_fPrice,g_lOpenDate,g_dwCardNo,lpszNameStr, lpnSysDoomType,uMsgID,m_pProgress局部变量应尽量易懂简洁,使用常见的变量,如
Num,nCount,i,j,k,n,len,pos, offset,nReadNum,index,nRet,ret, string,filename
临时变量,如ltmp,ftmp,tmpStr,tempStr,函数命名也应该见名知意。如CalcAllDataStyle(),ReadDocDataFromTime(),GetIndexInfo()
常见的函数
Init, OpenAll, Create_, Get_, Set_, Read_, Load_, Write_, Start_, Stop_, Check_, Test_, Fill_, Process_, Sort_, Do_, Select_, Is_, Exist_,_Ex。宏命名和typedef定义类型应详细,避免重复,一律为大写,如#define DEL_EMPTY(a) {if (a) {delete a;a=NULL;}}
#define SUCCESS 0
#define FAIL -1typedef struct
{
char lpzSource[100];
char lpzTitle[100];
char lpzURL[194];
short nType;
long npos;
long nlen;
}ATTBODY,*LPATTBODY; (指针前加LP)自定义消息从WM_USER开始
#define MYAPP_MESSAGE WM_USER+0x1001==============================================================
如上所言,并非完全正确,请从建议的角度、用怀疑的眼光批判地接收
命名应尽量使用匈牙利命名法,变量名或函数名中使用大写字符来区分各个部分,以便于记忆和阅读。如bPatchMinute, DeleteDirInfo()。全局(包括类中的)变量用长名字,局部变量用短名字。
类成员变量前一般应加上m_,全局变量加上g_,仅与本模块有关的变量加上l_,紧接着是变量的类型。
整型: n,i
长整型: l
无符号整型: u
无符号长整型:dw
字符: ch
布尔量: b
浮点数: f
双精度浮点: d
字符串: str,lpsz,sz,p,lp,ac,
指针: p
字节指针: pb
无符号指针: pv
字符指针: lpsz
整型指针: lpn
文件指针: fp
如:
m_nTotalNum,m_strPath,m_bRcving,m_fPrice,g_lOpenDate,g_dwCardNo,lpszNameStr, lpnSysDoomType,uMsgID,m_pProgress局部变量应尽量易懂简洁,使用常见的变量,如
Num,nCount,i,j,k,n,len,pos, offset,nReadNum,index,nRet,ret, string,filename
临时变量,如ltmp,ftmp,tmpStr,tempStr,函数命名也应该见名知意。如CalcAllDataStyle(),ReadDocDataFromTime(),GetIndexInfo()
常见的函数
Init, OpenAll, Create_, Get_, Set_, Read_, Load_, Write_, Start_, Stop_, Check_, Test_, Fill_, Process_, Sort_, Do_, Select_, Is_, Exist_,_Ex。宏命名和typedef定义类型应详细,避免重复,一律为大写,如#define DEL_EMPTY(a) {if (a) {delete a;a=NULL;}}
#define SUCCESS 0
#define FAIL -1typedef struct
{
char lpzSource[100];
char lpzTitle[100];
char lpzURL[194];
short nType;
long npos;
long nlen;
}ATTBODY,*LPATTBODY; (指针前加LP)自定义消息从WM_USER开始
#define MYAPP_MESSAGE WM_USER+0x1001==============================================================
如上所言,并非完全正确,请从建议的角度、用怀疑的眼光批判地接收
如:
iAge 代表int类型的变量,保存的是年龄
strMyName 代表String类型变量,保存的是姓名
Charles Simonyi
Microsoft CorporationReprinted November 1999Summary: Charles Simonyi’s explication of the Hungarian notation identifier naming convention. (10 printed pages)A note from Dr. GUI: Long, long ago in the early days of DOS, Microsoft’s Chief Architect Dr. Charles Simonyi introduced an identifier naming convention that adds a prefix to the identifier name to indicate the functional type of the identifier.This system became widely used inside Microsoft. It came to be known as “Hungarian notation” because the prefixes make the variable names look a bit as though they’re written in some non-English language and because Simonyi is originally from Hungary.As it turns out, the Hungarian naming convention is quite useful—it’s one technique among many that helps programmers produce better code faster. Since most of the headers and documentation Microsoft has published over the last 15 years have used Hungarian notation names for identifiers, many programmers outside of Microsoft have adopted one variation or another of this scheme for naming their identifiers.Perhaps the most important publication that encouraged the use of Hungarian notation was the first book read by almost every Windows programmer: Charles Petzold’s Programming Windows. It used a dialect of Hungarian notation throughout and briefly described the notation in its first chapter.MSDN is pleased to publish here the original edition of Simonyi’s historic work.Program Identifier Naming Conventions
This monograph is intended to give you the flavor of the major ideas behind the conventions. When confronted with the need for a new name in a program, a good programmer will generally consider the following factors to reach a decision: Mnemonic value—so that the programmer can remember the name.
Suggestive value—so that others can read the code.
“Consistency”—this is often viewed as an aesthetic idea, yet it also has to do with the information efficiency of the program text. Roughly speaking, we want similar names for similar quantities.
Speed of the decision—we cannot spend too much time pondering the name of a single quantity, nor is there time for typing and editing extremely long variable names.
All in all, name selection can be a frustrating and time consuming subtask. Often, a name that satisfies some of the above criteria will contradict the others. Maintaining consistency can be especially difficult. Advantages of the Conventions
The following naming conventions provide a very convenient framework for generating names that satisfy the above criteria. The basic idea is to name all quantities by their types. This simple statement requires considerable elaboration. (What is meant by “types”? What happens if “types” are not unique?) However, once we can agree on the framework, the benefits readily follow. The following are examples: The names will be mnemonic in a very specific sense: If someone remembers the type of a quantity or how it is constructed from other types, the name will be readily apparent.
The names will be suggestive as well: We will be able to map any name into the type of the quantity, hence obtaining information about the shape and the use of the quantity.
The names will be consistent because they will have been produced by the same rules.
The decision on the name will be mechanical, thus speedy.
Expressions in the program can be subjected to consistency checks that are very similar to the “dimension” checks in physics.
Type Calculus
As suggested above, the concept of “type” in this context is determined by the set of operations that can be applied to a quantity. The test for type equivalence is simple: could the same set of operations be meaningfully applied to the quantities in questions? If so, the types are thought to be the same. If there are operations that apply to a quantity in exclusion of others, the type of the quantity is different. The concept of “operation” is considered quite generally here; “being the subscript of array A” or “being the second parameter of procedure Position” are operations on quantity x (and A or Position as well). The point is that “integers” x and y are not of the same type if Position (x,y) is legal but Position (y,x) is nonsensical. Here we can also sense how the concepts of type and name merge: x is so named because it is an x-coordinate, and it seems that its type is also an x-coordinate. Most programmers probably would have named such a quantity x. In this instance, the conventions merely codify and clarify what has been widespread programming practice. Note that the above definition of type (which, incidentally, is suggested by languages such as SIMULA and Smalltalk) is a superset of the more common definition, which takes only the quantity’s representation into account. Naturally, if the representations of x and y are different, there will exist some operations that could be applied to x but not y, or the reverse. Let us not forget that we are talking about conventions that are to be used by humans for the benefit of humans. Capabilities or restrictions of the programming environment are not at issue here. The exact determination of what constitutes a “type” is not critical, either. If a quantity is incorrectly classified, we have a style problem, not a bug. Naming Rules
My thesis discusses in detail the following specific naming rules: Quantities are named by their type possibly followed by a qualifier. A convenient (and legal) punctuation is recommended to separate the type and qualifier part of a name. (In C, we use a capital initial for the qualifier as in rowFirst: row is the type; First is the qualifier.)
Qualifiers distinguish quantities that are of the same type and that exist within the same naming context. Note that contexts may include the whole system, a block, a procedure, or a data structure (for fields), depending on the programming environment. If one of the “standard qualifiers” is applicable, it should be used. Otherwise, the programmer can choose the qualifier. The choice should be simple to make, because the qualifier needs to be unique only within the type and within the scope—a set that is expected to be small in most cases. In rare instances more than one qualifier may appear in a name. Standard qualifiers and their associated semantics are listed below. An example is worthwhile: rowLast is a type row value; that is, the last element in an interval. The definition of Last states that the interval is “closed”; that is, a loop through the interval should include rowLast as its last value.
Simple types are named by short tags that are chosen by the programmer. The recommendation that the tags be small is startling to many programmers. The essential reason for short tags is to make the implementation of rule 4 realistic. Other reasons are listed below.
Names of constructed types should be constructed from the names of the constituent types. A number of standard schemes for constructing pointer, array, and different types exist. Other constructions may be defined as required. For example, the prefix p is used to construct pointers. prowLast is then the name of a particular pointer to a row type value that defines the end of a closed interval. The standard type constructions are also listed below.
A good yardstick for choosing a name is to try to imagine that there is an extraordinary reward for two programmers if they can independently come up with the same program text for the same problem. Both programmers know the reward, but cannot otherwise communicate. Such an experiment would be futile, of course, for any sizable problem, but it is a neat goal. The reward of real life is that a program written by someone else, which is identical to what one’s own program would have been, is extremely readable and modifiable. By the proper use of the conventions, the idea can be approached very closely, give or take a relatively few tags and possibly some qualifiers. The leverage of the tags is enormous. If they are communicated, are agreed on beforehand, or come from a common source, the goal becomes reachable and the reward may be reaped. This makes the documentation of the tags all the more important. An example of such a consideration is the discretionary use of qualifiers in small scopes where a quantity’s type is likely to be unique, for example in small procedures with a few parameters and locals or in data structures which typically have only a few fields. One might prefer to attach a qualifier even to a quantity with a unique type of “writability,” the ability for someone else to come up with the name without hesitation. As many textbooks point out, the “someone else” can be the same programmer sometime in the future revisiting the long-forgotten code.Conclusion Do not use qualifiers when not needed, even if they seem valuable
Unfortunately, the simple notion of qualified typed tags does not work well for procedure names. Some procedures do not take parameters or do not return values. The scopes of procedure names tend to be large. The following set of special rules for procedures has worked quite satisfactorily: Distinguish procedure names from other names by punctuation, for example by always starting with a capital letter (typed tags of other quantities are in lower case). This alleviates the problem caused by the large scope.
Start the name with the tag of the value that is returned, if any.
Express the action of the procedure in one or two words, typically transitive verbs. The words should be punctuated for easy parsing by the reader (a common legal method of punctuation is the use of capital initials for every word).
Append the list of tags of some or all of the formal parameters if it seems appropriate to do so.
The last point is contrary to the earlier res on data structure naming. When the parameters to a procedure are changed, typically all uses of the procedure will need to be updated. There is an opportunity during the update to change the name as well. In fact, the name change can serve as a useful check that all occurrences have been found. With data structures, the addition or change of a field will not have an effect on all uses of the changed structure type. Typically, if a procedure has only one or two parameters, the inclusion of the parameter tags will really simplify the choice of procedure name. Table 1. Some examples for procedure namesName Description
InitSy Takes an sy as its argument and initializes it.
OpenFn fn is the argument. The procedure will “open” the fn. No value is returned.
FcFromBnRn Returns the fc corresponding to the bn,rn pair given. (The names cannot tell us what the types sy, fn, fc, and so on, are.) The following is a list of standard type constructions. (X and Y stand for arbitrary tags. According to standard punctuation, the actual tags are lowercase.) Table 2. Standard type constructionspX Pointer to X.
dX Difference between two instances of type X. X + dX is of type X.
cX Count of instances of type X.
mpXY An array of Ys indexed by X. Read as “map from X to Y.”
rgX An array of Xs. Read as “range X.” The indices of the array are called:
iX
index of the array rgX.
dnX (rare) An array indexed by type X. The elements of the array are called:
eX
(rare) Element of the array dnX.
grpX A group of Xs stored one after another in storage. Used when the X elements are of variable size and standard array indexing would not apply. Elements of the group must be referenced by means other then direct indexing. A storage allocation zone, for example, is a grp of blocks.
bX Relative offset to a type X. This is used for field displacements in a data structure with variable size fields. The offset may be given in terms of bytes or words, depending on the base pointer from which the offset is measured.
cbX Size of instances of X in bytes.
cwX Size of instances of X in words. Where it matters, quantities named mp, rg, dn, or grp are actually pointers to the structures described above. One obvious problem with the constructions is that they make the parsing of the types ambiguous. Is pfc a tag of its own or is it a pointer to an fc? Such questions can be answered only if one is familiar with the specific tags that are used in a program. The following are standard qualifiers. (The letter X stands for any type tag. Actual type tags are in lowercase.)Table 3. Standard qualifiersXFirst The first element in an ordered set (interval) of X values.
XLast The last element in an ordered set of X values. XLast is the upper limit of a closed interval, hence the loop continuation condition should be: X <= XLast.
XLim The strict upper limit of an ordered set of X values. Loop continuation should be: X < XLim.
XMax Strict upper limit for all X values (excepting Max, Mac, and Nil) for all other X: X < XMax. If X values start with X=0, XMax is equal to the number of different X values. The allocated length of a dnx vector, for example, will be typically XMax.
XMac The current (as opposed to constant or allocated) upper limit for all X values. If X values start with 0, XMac is the current number of X values. To iterate through a dnx array, for example:
for x=0 step 1 to xMac-1 do ... dnx[x] ...
or
for ix=0 step 1 to ixMac-1 do ... rgx[ix] ...
XNil A distinguished Nil value of type X. The value may or may not be 0 or -1.
XT Temporary X. An easy way to qualify the second quantity of a given type in a scope. Table 4. Some common primitive typesf Flag (Boolean, logical). If qualifier is used, it should describe the true state of the flag. Exception: the constants fTrue and fFalse.
w Word with arbitrary contents.
ch Character, usually in ASCII text.
b Byte, not necessarily holding a coded character, more akin to w. Distinguished from the b constructor by the capital letter of the qualifier in immediately following.
sz Pointer to first character of a zero terminated string.
st Pointer to a string. First byte is the count of characters cch.
h pp (in heap). The following partial example of an actual symbol table routine illustrates the use of the conventions in a “real life” situation. The purpose of this example is not to make any claims about the code itself, but to show how the conventions can help us learn about the code. In fact, some of the names in this routine are standard.