Copyright 1995 D. Hanson, K. Li & J.P. Singh Computer Science 217: Programming Style Page 106 October 12, 1997 Programming Style• Writing good programs is like writing good prose; the object is to communicate concise, straightforward, no unnecessary parts • Principles of good programming style are language independent some languages have features that encourage good style, e.g. structured loopssome have features that discourage good style, e.g. gotos, anemic data typesmodern block-structured languages are better than older unstructured languagesbut bad programs can be written in any language • Benefits of good style code that is easy to understand code that is more likely to work code that is easy to maintain and change • Method to develop good programming style read code written by good programmersAsk: Will I understand this program in two years?Copyright 1995 D. Hanson, K. Li & J.P. Singh Computer Science 217: Programming Style Page 107 October 12, 1997 Names• Pick names that capture the use of the variable or function, e.g. addElement nouns for variablesverbs for functionsadjectives for booleans, conditions, and some enumeration constants • Use descriptive names for global variables and functions, e.g. elementCount • Use concise names for local variables that reflect standard notation prefer to for (i = 0; i < n; i++)a[i] = 0; • Use case judiciously use all capitals for constantsdon’t rely on only case to distinguish names • Use a consistent style for compound names printword PrintWord print_word • Module-level prefixes help distinguish names, e.g. Strset_T, Strset_add • Don’t use nerdy abbreviations and acronyms for (arrayindex = 0; arrayindex<arraysize; arrayindex++)array[arrayindex] = 0;Copyright 1995 D. Hanson, K. Li & J.P. Singh Computer Science 217: Programming Style Page 108 October 12, 1997 Layout and Indentation• Use white space judiciously separate code into “paragraphs”make expressions more readable • Use indentation to emphasize structure use editor “autoindent” facilities and a consistent amount of spacewatch for extreme indentation — signals excessive nesting • Line up parallel structures alpha = angle(p1, p2, p3); beta = angle(p2, p3, p1); gamma = angle(p3, p1, p2); • One statement per line • Be consistent , but use variation for emphasis • Break long lines at logical places, e.g. by precedence; indent continuations • Use tabular input and output formats alpha = angle(p1, p2, p3);beta = angle(p2, p3, p1);gamma = angle(p3, p1, p2)Copyright 1995 D. Hanson, K. Li & J.P. Singh Computer Science 217: Clear Expression Page 109 October 12, 1997 Clear Expression• Compare: for(i=1; i<=n; i++)for(j=1; j<=n; i++)v[i-1][j-1] = (i/j)*(j/i); vs. /* make v the identity matrix */for (i = 0; i < n; i++) {for (j = 0; j < n; j++)v[i][j] = 0.0;v[i][i] = 1.0;} • Rules: be clever, but don’t be too clever say what you mean, simply and directlyuse parentheses to emphasize precedence and braces to display structureuse white space and indentation to clarify structuredon’t sacrifice clarity for “efficiency”Copyright 1995 D. Hanson, K. Li & J.P. Singh Computer Science 217: Clear Expression Page 110 October 12, 1997 Clear Expression, cont’d• Compare: if (!(i > 10 || 0 > i)) ... vs. if (0 <= i && i <= 10) ... • Compare: for (neg = 0; *s1 == *s2++; )if (*s1++ == '\0')break;neg = *s1 - (*--s2);if (!neg) ... vs. while (*s1 == *s2 && *s1 != '\0') { s1++; s2++; }if (*s1 == *s2) ... vs. if (strcmp(s1, s2) == 0) ... • Rules: avoid double negationavoid temporary variablesuse library functionslet the compiler do the dirty workCopyright 1995 D. Hanson, K. Li & J.P. Singh Computer Science 217: Clear Expression Page 111 October 12, 1997 Clear Expression, cont’d• Compare: if (a > b) vs. if (b > c)z = c;elsez = b;elseif (a > c)z = c;elsez = a; better yet: z = min(a, min(b, c)); • Rules: lay out expressions according to standard conventions rearrange logic so it is easy to understand follow each decision with a matching action if (a < b)if (b <= c)z = a;elsez = c;else /* a >= b *if (b <= c)z = belsez = c;Copyright 1995 D. Hanson, K. Li & J.P. Singh Computer Science 217: Clear Expression Page 112 October 12, 1997 Control Structure• Flow of control should be written for human understanding for (i = 0; i < n; i++) {if (strcmp(table[i].word, word)) continue;table[i].count++;} better: for (i = 0; i < n; i++)if (strcmp(table[i].word, word) == 0)table[i].count++; • Avoid continue; break is OK, but use it sparingly;“breaking” out of functions is OK, if used with care • Rules: use structured control constructsdon’t make the reader jump around or decrypt convoluted flow of controlavoid long blocksavoid complicated, nested blocksminimize the use of return and break func(a) {if (isbad(a))return;...}Copyright 1995 D. Hanson, K. Li & J.P. Singh Computer Science 217: Clear Expression Page 113 October 12, 1997 Control Structure, cont’d• “Comb” structures compare: vs: if (x < v[mid])high = mid - 1;else if (x > v[mid])low = mid + 1;elsereturn mid; • Ditto for switch • Rules: implement multiway branches with if ... else if ... else emphasize that only one of the actions is performedavoid empty then and else actionshandle default action, even if it “can’t happen;” use assert(0) avoid nesting if (x < v[mid])high = mid - 1;else if (x > v[mid])low = mid + 1;elsereturn mid;Copyright 1995 D. Hanson, K. Li & J.P. Singh Computer Science 217: Clear Expression Page 114 October 12, 1997 Program Structure• Rules: modularize; use interfacesevery function/interface should do one thing wellevery function/interface should hide somethingreplace repetitious code with calls to functionslet the data structure the programmake sure your code “does nothing” gracefullydon’t patch bad code — rewrite itdon’t strain to reuse code — reorganize itwatch for “off-by-one” errorsCopyright 1995 D. Hanson, K. Li & J.P. Singh Computer Science 217: Clear Expression Page 115 October 12, 1997 Documentation• Best program documentation includes clean structureconsistent programminggood mnemonic identifierssmattering of enlighting comments • Comments should add new information i = i + 1; /* add one to i */ • Comments and code must agree ; if they disagree, odds are they are both wrong • Don’t comment bad code — rewrite it • Comment algorithms, not
View Full Document