The Psychology of Quality and More |
CHAPTER 5 : Naming
5.9 Indicating typeSome advantage may be gained from indicating the type of the variable in its name. A common example is the suffix 'ptr' used to indicate a pointer:
ParaPtr, FirstFreeBlockPtr ---------------------------------------------------- An alternative approach (sometimes known as the 'Hungarian' method), which can be used to indicate any type, is to prefix the name with a lower case letter:
pPara, pFirstFreeBlock
This reads naturally: "pointer to a paragraph", "Pointer to the first free block". It also helps to know immediately that the variable is a pointer, putting it directly into context. Even more so than functional prefixes, a type indicator needs to be differentiated from the name. The lowercase letter works well with a following capital. An alternative, which would work with a lowercase naming scheme, is to separate the type identifier with an underscore, possibly also making it a suffix:
para_p, first_free_block_p
The type of any item can be indicated in a similar manner. The only important rules are (a) to be consistent and (b) to make sure that the set of prefixes and their use are clearly documented. Candidates include:
Prefix Meaning b Boolean c Character i Integer l Long u Unsigned p Pointer a Array f Bit flags h File Handle z Zero terminated character array s structure
Note that using the 'b' prefix for boolean can be an alternative to using 'Is' as above (see 5.8.2), thus:
bDoorOpen ...or... DoorIsOpen
Type prefixes can show up some potential problems in the code, and undesirable or illegal operations become immediately visible.
aEmpNames[0] = '\0'; /* this is ok */
Types can be combined, thus 'int *apWidgetSizes[]' is an array of pointers to integers. Thus rather than having to work out what 'WidgetSizes' is from the context, it is clear from the name. The type of return from a function can similarly be shown with a prefix. Thus a function returning a pointer to a structure might be 'psGetWindow()'.
This prefixing method can be confusing, especially where there are many prefixes to learn, where they are used in combination with a functional prefix, or with an all-lower case naming standard. Also, where the variable has a relatively short scope, the use of such prefixing has less value. A compromise is to define a limited set for types which are most likely to cause confusion and error. e.g:
Prefix Meaning p pointer a array h handle u unsigned
This book uses only 'p' as a prefix for pointers.
|
Site Menu |
Quality: | Quality Toolbook | Tools of the Trade | Improvement Encyclopedia | Quality Articles | Being Creative | Being Persuasive | |
And: | C Style (Book) | Stories | Articles | Bookstore | My Photos | About | Contact | |
Settings: | Computer layout | Mobile layout | Small font | Medium font | Large font | Translate | |
You can buy books here |
And the big |