Good ProgrammingOverview of Today’s ClassProgramming StyleSelf-Documenting Code!Programming StyleConvey Structure: Space and IndentingRepresent Code in “Paragraphs”Use Natural Form for ExpressionsParenthesize to Resolve AmbiguityAnother Example With ParenthesesBreak Up Complex ExpressionsUse Consistent IndentationUse Common C IdiomsUse “else-if” for Multi-way DecisionFollow Consistent Naming StyleDocumentationModularityDividing Programs into ModulesAn Example: Text FormattingExample Input and OutputThinking About the ProblemSubdividing the ProgramPseudocode for the Main ProgramMain Program: Format TextMain Program: “Do Stuff”Words: Reading a CharacterWords: Reading a WordLines: Key FunctionsLines: Getting StartedLines: Simple Book-keeping Lines: Add a Word to a LineLines: Print Without JustificationLines: Print Line With JustificationLines: Print Line With JustificationModularity: Summary of ExampleConclusions1Good ProgrammingProf. David AugustCOS 2172Overview of Today’s Class• Programming styleo Layout and indentationo Variable nameso Documentation• Modularityo Moduleso Interface and implementationo Example: left and right justifying text3Programming Style• Who reads your code?o Compilero Other programmers• Which of these cares about style?typedef struct{double x,y,z}vec;vec U,black,amb={.02,.02,.02};struct sphere{ vec cen,color;double rad,kd,ks,kt,kl,ir}*s,*best,sph[]={0.,6.,.5,1.,1.,1.,.9, .05,.2,.85,0.,1.7,-1.,8.,-.5,1.,.5,.2,1.,.7,.3,0.,.05,1.2,1.,8.,-.5,.1,.8,.8, 1.,.3,.7,0.,0.,1.2,3.,-6.,15.,1.,.8,1.,7.,0.,0.,0.,.6,1.5,-3.,-3.,12.,.8,1., 1.,5.,0.,0.,0.,.5,1.5,};yx;double u,b,tmin,sqrt(),tan();double vdot(A,B)vec A ,B;{return A.x*B.x+A.y*B.y+A.z*B.z;}vec vcomb(a,A,B)double a;vec A,B;{B.x+=a* A.x;B.y+=a*A.y;B.z+=a*A.z;return B;}vec vunit(A)vec A;{return vcomb(1./sqrt( vdot(A,A)),A,black);}struct sphere*intersect(P,D)vec P,D;{best=0;tmin=1e30;s= sph+5;while(s--sph)b=vdot(D,U=vcomb(-1.,P,s-cen)),u=b*b-vdot(U,U)+s-rad*s -rad,u=u0?sqrt(u):1e31,u=b-u1e-7?b-u:b+u,tmin=u=1e-7&&u<tmin?best=s,u: tmin;return best;}vec trace(level,P,D)vec P,D;{double d,eta,e;vec N,color; struct sphere*s,*l;if(!level--)return black;if(s=intersect(P,D));else return amb;color=amb;eta=s-ir;d= -vdot(D,N=vunit(vcomb(-1.,P=vcomb(tmin,D,P),s-cen)));if(d<0)N=vcomb(-1.,N,black),eta=1/eta,d= -d;l=sph+5;while(l--sph)if((e=l -kl*vdot(N,U=vunit(vcomb(-1.,P,l-cen))))0&&intersect(P,U)==l)color=vcomb(e ,l-color,color);U=s-color;color.x*=U.x;color.y*=U.y;color.z*=U.z;e=1-eta* eta*(1-d*d);return vcomb(s-kt,e0?trace(level,P,vcomb(eta,D,vcomb(eta*d-sqrt(e),N,black))):black,vcomb(s-ks,trace(level,P,vcomb(2*d,N,D)),vcomb(s-kd, color,vcomb(s-kl,U,black))));}main(){printf("%d %d\n",32,32);while(yx<32*32) U.x=yx%32-32/2,U.z=32/2-yx++/32,U.y=32/2/tan(25/114.5915590261),U=vcomb(255., trace(3,black,vunit(U)),black),printf("%.0f %.0f %.0f\n",U);}This is a working ray tracer! (courtesy of Paul Heckbert)4Self-Documenting Code!5Programming Style• Why does programming style matter?o Bugs are often caused by programmer’s misunderstanding – What does this variable do?– How is this function called?o Good code = human readable code• How can code become easier for humans to read?o Structureo Conventionso Documentationo Modularity6Convey Structure: Space and Indenting• Example: Assign each array element a[j] to the value j.• Bad code• Good code• Can often rely on auto-indenting feature in editorfor (j=0;j<100;j++) a[j]=j;for (j=0; j<100; j++) a[j] = j;7Represent Code in “Paragraphs”• Use blank lines to divide the code into key parts#include <termios.h>#include <unistd.h>int main(int argc, char **argv) {/* Set the input to no-echo, character-at-time * ("cbreak") mode, * and remember the old mode in t0 */struct termios t0, t1;tcgetattr(0,&t0);t1 = t0;t1.c_lflag &= !(ECHO|ICANON);tcsetattr(0,0,&t1);run();/* Set the terminal back to its original mode */tcsetattr(0,0,&t0);return 0;}8Use Natural Form for Expressions• Example: Check if integer n satisfies j < n < k• Bad code• Good code• Conditions should read like you’d say them aloudo Not “Conditions shouldn’t read like you’d never say them aloud”!if (!(n >= k) && !(n <= j))if ((n > j) && (n < k))9Parenthesize to Resolve Ambiguity• Example: Check if integer n satisfies j < n < k• Bad code• Good code• Better to make the groupings explicito Relational operators (e.g., “>”) have precedence over logical operators (e.g., “ &&”), but who can remember these things?if ((n > j) && (n < k)) if (n > j && n < k)10Another Example With Parentheses• Example: Read and print character until the end-of-file.•Right code• Wrong code (what will it do???)• Must make the grouping explicito Logical operators (e.g., “!=“) have precedence over assignment (“=“)while (c = getchar() != EOF)putchar(c);while ((c = getchar()) != EOF)putchar(c);11Break Up Complex Expressions• Example: Identify chars corresponding to months of year.• Bad code• Good code• Lining up the parallel structures is helpful, too!if ((c == ‘J’) || (c == ‘F’) || (c == ‘M‘) || (c == ‘A’) || (c == ‘S’) || (c == ‘O’) || (c == ‘N’) || (c == ‘D’)) if ((c == ‘J’) || (c == ‘F’) || (c == ‘M‘) || (c == ‘A’) || (c == ‘S’) || (c == ‘O’) || (c == ‘N’) || (c == ‘D’))12Use Consistent Indentation• Example: Checking for leap year (does Feb 29 exist?).if (month == FEB) {if (year & 4 == 0) if (day > 29)legal = FALSE;else if (day > 28)legal = FALSE;} if (month == FEB) {if (year & 4 == 0) {if (day > 29)legal = FALSE;}else {if (day > 28)legal = FALSE;}} Wrong code (else matches “if day > 29”)Right code Note: The “&” means “mod”13Use Common C Idioms• Example: Set each array element to 1.0.• Bad code (or, perhaps just “so-so” code)• Good codei = 0;while (i <= n-1)array[i++] = 1.0;for (i=0; i<n; i++)array[i] = 1.0;14Use “else-if” for Multi-way Decision• Example: Comparison step in a binary search.• Bad code• Good codeif (x < v[mid])high = mid – 1; else if (x > v[mid])low = mid + 1; elsereturn mid; if (x < v[mid])high = mid – 1;else if (x > v[mid])low = mid + 1;elsereturn mid;245781017low=0high=6mid=310xv15Follow Consistent Naming Style• Descriptive names for globals and functionso E.g., display, CONTROL, CAPACITY• Concise names for local variableso E.g., i (not arrayindex) for loop variable• Use case judiciouslyo E.g., Buffer_insert
View Full Document