11.2. Naming Specific Types of Data

 < Free Open Study > 

In addition to the general considerations in naming data, special considerations come up in the naming of specific kinds of data. This section describes considerations specifically for loop variables, status variables, temporary variables, boolean variables, enumerated types, and named constants.

Naming Loop Indexes

Cross-Reference

For details on loops, see Chapter 16, "Controlling Loops."


Guidelines for naming variables in loops have arisen because loops are such a common feature of computer programming. The names i, j, and k are customary:

Java Example of a Simple Loop Variable Name
for ( i = firstItem; i < lastItem; i++ ) {    data[ i ] = 0; }

If a variable is to be used outside the loop, it should be given a name more meaningful than i, j, or k. For example, if you are reading records from a file and need to remember how many records you've read, a name like recordCount would be appropriate:

Java Example of a Good Descriptive Loop Variable Name
recordCount = 0; while ( moreScores() ) {    score[ recordCount ] = GetNextScore();    recordCount++; } // lines using recordCount ...

If the loop is longer than a few lines, it's easy to forget what i is supposed to stand for and you're better off giving the loop index a more meaningful name. Because code is so often changed, expanded, and copied into other programs, many experienced programmers avoid names like i altogether.

One common reason loops grow longer is that they're nested. If you have several nested loops, assign longer names to the loop variables to improve readability.

Java Example of Good Loop Names in a Nested Loop
for ( teamIndex = 0; teamIndex < teamCount; teamIndex++ ) {    for ( eventIndex = 0; eventIndex < eventCount[ teamIndex ]; eventIndex++ ) {       score[ teamIndex ][ eventIndex ] = 0;    } }

Carefully chosen names for loop-index variables avoid the common problem of index cross-talk: saying i when you mean j and j when you mean i. They also make array accesses clearer: score[ teamIndex ][ eventIndex ] is more informative than score[ i ][ j ].

If you have to use i, j, and k, don't use them for anything other than loop indexes for simple loops the convention is too well established, and breaking it to use them in other ways is confusing. The simplest way to avoid such problems is simply to think of more descriptive names than i, j, and k.

Naming Status Variables

Status variables describe the state of your program. Here's a naming guideline:

Think of a better name than flag for status variables It's better to think of flags as status variables. A flag should never have flag in its name because that doesn't give you any clue about what the flag does. For clarity, flags should be assigned values and their values should be tested with enumerated types, named constants, or global variables that act as named constants. Here are some examples of flags with bad names:

C++ Examples of Cryptic Flags

if ( flag ) ... if ( statusFlag & 0x0F ) ... if ( printFlag == 16 ) ... if ( computeFlag == 0 ) ... flag = 0x1; statusFlag = 0x80; printFlag = 16; computeFlag = 0;


Statements like statusFlag = 0x80 give you no clue about what the code does unless you wrote the code or have documentation that tells you both what statusFlag is and what 0x80 represents. Here are equivalent code examples that are clearer:

C++ Examples of Better Use of Status Variables
if ( dataReady ) ... if ( characterType & PRINTABLE_CHAR ) ... if ( reportType == ReportType_Annual ) ... if ( recalcNeeded == True ) ... dataReady = true; characterType = CONTROL_CHARACTER; reportType = ReportType_Annual; recalcNeeded = false;

Clearly, characterType = CONTROL_CHARACTER is more meaningful than statusFlag = 0x80. Likewise, the conditional if ( reportType == ReportType_Annual ) is clearer than if ( printFlag == 16 ). The second example shows that you can use this approach with enumerated types as well as predefined named constants. Here's how you could use named constants and enumerated types to set up the values used in the example:

Declaring Status Variables in C++
// values for CharacterType const int LETTER = 0x01; const int DIGIT = 0x02; const int PUNCTUATION = 0x04; const int LINE_DRAW = 0x08; const int PRINTABLE_CHAR = ( LETTER | DIGIT | PUNCTUATION | LINE_DRAW ); const int CONTROL_CHARACTER = 0x80; // values for ReportType enum ReportType {    ReportType_Daily,    ReportType_Monthly,    ReportType_Quarterly,    ReportType_Annual,    ReportType_All };

When you find yourself "figuring out" a section of code, consider renaming the variables. It's OK to figure out murder mysteries, but you shouldn't need to figure out code. You should be able to read it.

Naming Temporary Variables

Temporary variables are used to hold intermediate results of calculations, as temporary placeholders, and to hold housekeeping values. They're usually called temp, x, or some other vague and nondescriptive name. In general, temporary variables are a sign that the programmer does not yet fully understand the problem. Moreover, because the variables are officially given a "temporary" status, programmers tend to treat them more casually than other variables, increasing the chance of errors.

Be leery of "temporary" variables It's often necessary to preserve values temporarily. But in one way or another, most of the variables in your program are temporary. Calling a few of them temporary may indicate that you aren't sure of their real purposes. Consider the following example:

C++ Example of an Uninformative "Temporary" Variable Name
// Compute roots of a quadratic equation. // This assumes that (b^2-4*a*c) is positive. temp = sqrt( b^2 - 4*a*c ); root[0] = ( -b + temp ) / ( 2 * a ); root[1] = ( -b - temp ) / ( 2 * a );

It's fine to store the value of the expression sqrt( b^2 - 4 * a * c ) in a variable, especially since it's used in two places later. But the name temp doesn't tell you anything about what the variable does. A better approach is shown in this example:

C++ Example with a "Temporary" Variable Name Replaced with a Real Variable
// Compute roots of a quadratic equation. // This assumes that (b^2-4*a*c) is positive. discriminant = sqrt( b^2 - 4*a*c ); root[0] = ( -b + discriminant ) / ( 2 * a ); root[1] = ( -b - discriminant ) / ( 2 * a );

This is essentially the same code, but it's improved with the use of an accurate, descriptive variable name.

Naming Boolean Variables

Following are a few guidelines to use in naming boolean variables:

Keep typical boolean names in mind Here are some particularly useful boolean variable names:

  • done Use done to indicate whether something is done. The variable can indicate whether a loop is done or some other operation is done. Set done to false before something is done, and set it to true when something is completed.

  • error Use error to indicate that an error has occurred. Set the variable to false when no error has occurred and to true when an error has occurred.

  • found Use found to indicate whether a value has been found. Set found to false when the value has not been found and to true once the value has been found. Use found when searching an array for a value, a file for an employee ID, a list of paychecks for a certain paycheck amount, and so on.

  • success or ok Use success or ok to indicate whether an operation has been successful. Set the variable to false when an operation has failed and to true when an operation has succeeded. If you can, replace success with a more specific name that describes precisely what it means to be successful. If the program is successful when processing is complete, you might use processingComplete instead. If the program is successful when a value is found, you might use found instead.

Give boolean variables names that imply true or false Names like done and success are good boolean names because the state is either true or false; something is done or it isn't; it's a success or it isn't. Names like status and sourceFile, on the other hand, are poor boolean names because they're not obviously true or false. What does it mean if status is true? Does it mean that something has a status? Everything has a status. Does true mean that the status of something is OK? Or does false mean that nothing has gone wrong? With a name like status, you can't tell.

For better results, replace status with a name like error or statusOK, and replace sourceFile with sourceFileAvailable or sourceFileFound, or whatever the variable represents.

Some programmers like to put Is in front of their boolean names. Then the variable name becomes a question: isdone? isError? isFound? isProcessingComplete? Answering the question with true or false provides the value of the variable. A benefit of this approach is that it won't work with vague names: isStatus? makes no sense at all. A drawback is that it makes simple logical expressions less readable: if ( isFound ) is slightly less readable than if ( found ).

Use positive boolean variable names Negative names like notFound, notdone, and notSuccessful are difficult to read when they are negated for example,

if not notFound

Such a name should be replaced by found, done, or processingComplete and then negated with an operator as appropriate. If what you're looking for is found, you have found instead of not notFound.

Naming Enumerated Types

Cross-Reference

For details on using enumerated types, see Section 12.6, "Enumerated Types."


When you use an enumerated type, you can ensure that it's clear that members of the type all belong to the same group by using a group prefix, such as Color_, Planet_, or Month_. Here are some examples of identifying elements of enumerated types using prefixes:

Visual Basic Example of Using a Prefix Naming Convention for Enumerated Types
Public Enum Color    Color_Red    Color_Green    Color_Blue End Enum Public Enum Planet    Planet_Earth    Planet_Mars    Planet_Venus End Enum Public Enum Month    Month_January    Month_February    ...    Month_December End Enum

In addition, the enum type itself (Color, Planet, or Month) can be identified in various ways, including all caps or prefixes (e_Color, e_Planet, or e_Month). A person could argue that an enum is essentially a user-defined type and so the name of the enum should be formatted the same as other user-defined types like classes. A different argument would be that enums are types, but they are also constants, so the enum type name should be formatted as constants. This book uses the convention of mixed case for enumerated type names.

In some languages, enumerated types are treated more like classes, and the members of the enumeration are always prefixed with the enum name, like Color.Color_Red or Planet.Planet_Earth. If you're working in that kind of language, it makes little sense to repeat the prefix, so you can treat the name of the enum type itself as the prefix and simplify the names to Color.Red and Planet.Earth.

Naming Constants

Cross-Reference

For details on using named constants, see Section 12.7, "Named Constants."


When naming constants, name the abstract entity the constant represents rather than the number the constant refers to. FIVE is a bad name for a constant (regardless of whether the value it represents is 5.0). CYCLES_NEEDED is a good name. CYCLES_NEEDED can equal 5.0 or 6.0. FIVE = 6.0 would be ridiculous. By the same token, BAKERS_DOZEN is a poor constant name; DONUTS_MAX is a good constant name.

 < Free Open Study > 


Code Complete
Code Complete: A Practical Handbook of Software Construction, Second Edition
ISBN: 0735619670
EAN: 2147483647
Year: 2003
Pages: 334

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net