Naming

From 太極
Jump to navigation Jump to search

Google C++ Style Guide

http://google-styleguide.googlecode.com/svn/trunk/cppguide.html

The Practice of Programming

Naming

  • Use capital letter for constant
#define ONE 1
  • Include a brief comment with the declaration of each global
  • Use descriptive names for global.
int npending = 0; // current length of input queue
  • Use short names for locals. Compare
for (theElementIndex = 0; theElementIndex < numberOfElements; theElementIndex++)
  elementArray[theElementIndex] = theElementIndex;

to

for (int i =0; i < nelems; i++)
   elem[i] = i;
  • Other naming conventions and local customs.
    • Use names that begin or end with p, such as nodep, for pointers;
    • Initial capital letters for globals;
    • All capitals for constants;
    • Use pch to mean a pointer to a character;
    • strTo and strFrom to mean strings that will be written to and read from;
    • It is a matter of taste as for the spelling of the names themselves: npending or or numPending or num_pending.
  • Be consistent. Give related things related names that show their relationship and highlight their difference. For example
class UserQueue {
  int noOfItemsInQ, frontOfTheQueue, queueCapacity;
  public int noOfUsersInQueue() { ... }
}

can be better changed to

class UserQueue {
  int nitems, front, capacity;
  public int nusers() { ... }
}
  • Use active name for functions. Functions names should be based on active verbs, perhaps followed by nouns:
now = date.getTime();
putchar('\n');

Functions that return a boolean value should be named so that the return value is unambiguous. Thus

if (checkoctal(c)) ...

does not indicate which value is true and which is false, while

if (isoctal(c)) ...

makes it clear that the function returns true if the argument is octal and false if not.

  • Be accurate. A name not only labels, it conveys information to the reader. For example, the function name below is doing the opposite of what it has been implemented.
public boolean inTable(Object obj) {
  int j = this.getIndex(obj);
  return( j == nTable);
}

Expressions and Statements

  • Indent to show structure
  • Use the natural form for expressions.
if (!(block_id < actblks) || !(block_id >= unblocks)) ...

is not good compare with

if ((block_id > actblks) || (block_id < unblocks)) ...
  • Parenthesize to resolve ambiguity.
  • Break up complex expressions
  • Be clear. For example ?: operator is fine for short expressions , as in
max = (a > b) ? a : b;
printf("The list has %d item%s\n", n , n==1 ? "" : "s");

but it is not general replacement for conditional statements.

  • Be careful with side effects. For example, the '++' operator and I/O. For example, the following is wrong because all the arguments to scanf are evaluated before the routine is called.
scanf("%d %d", &yr, &profit[yr])

The fix is

scanf("%d", &yr);
scanf("%d", &profit[yr]);

Consistency and Idioms

  • Use a consistent indentation and brace style.
  • Use idioms for consistency. For example,
for(int i = 0; i < n; i++)
    array[i] = 1.0;

is better than

// Form 1
int i = 0;
while (i <= n-1)
    array[i++] = 1.0;
// Form 2
int i;
for (i = 0; i < n; )
    array[i++] = 1.0;
// Form 3
int i;
for (i = 0; i < n; i++)
    array[i] = 1.0;

Other standard idioms include

for (p = list; p != NULL; p = p->next) ...
for (;;) ...

Another commom idiom is to nest an assignment inside a loop condition, as in

while ((c = getchar() != EOF)
    putchar(c);

Another example (wrong code, the error may not be detected until the damage has been done.) is

int i, *iArray, nmemb;
iArray = malloc(nmmeb * sizeof(int));
for (i = 0; i <= nmemb; i++)
    iArray[i] = i;

The following code

char *p, buf[256];
gets(buf);
p = malloc(strlen(buf));
strcpy(p, buf);

should be replaced by

p = malloc(strlen(buf) + 1);
strcpy(p, buf);
// OR
p = new char[strlen(buf)+1];
strcpy(p, buf);
  • Use Use else-ifs for multi-way decision.

Function Macros

  • Avoid function macros.
  • Parenthszie the macro body and arguments. A macro like this,
#define square(x)  (x) * (x)

the expression 1/square(x) will be expanded to the erroneous

1 / (x) * (x)

The macro should be rewritten as

#define square(x)  ((x) * (x))

Magic Numbers

  • Give names to magic numbers.
enum {
    MINROW    = 1,               /* top edge */
    MINCOL    = 1,               /* left edge */
    MAXROW    = 24,              /* bottom edge */
    HEIGHT    = MAXROW - 4,      /* height of bars */
    WIDTH     = (MAXCOL-1)/NLET  /* width of bars */
};
...
fac = (lim + HEIGHT-1) / HEIGHT; 
  • Define numbers as constants, not macros. The macros like #define are dangerous way to program because they change the lexical structure of the program underfoot.
const int MAXROW = 24, MAXCOL = 80;

C also has const values but they cannot be used as array bounds, so the enum statement remains the method of choice in C.

  • Use character constants, not integers.Or better to use the library.
if (c >= 65 && c <= 90)    // not good
if (c >= 'A' && c <= 'Z')  // better
if (isupper(c))            // best

The number 0 should be avoided in certain situations. For example, use (void*)0 or NULL to represent a zero pointer in C, and '\0' instead of 0 to represent the null byte at the end of a string. In other words, don't write

str = 0;
name[i] = 0;
x = 0;

but rather:

str = NULL;
name[i] = '\0';
x = 0.0;

However, in C++, 0 rather than NULL is the accepted notation for a null pointer.

  • Use the language to calculate the size of an object. Don't use an explicit size for any data type: use sizeof(int) instead of 2 or 4, for instance.

Comments

  • Don't belabor the obvious.
  • Comments functions and global data.
  • Don't comment bad code, rewrite it.
  • Don't contradict the code.
  • Clarify, don't confuse.