M-1M-1University of WashingtonComputer Programming IProgram Style© 2000 UW CSEM-2Aspects of Quality SoftwareGetting the syntax rightThis may seem hard at first, but turns out to be the easiest part of allGetting the logic rightSometimes difficult, but absolutely essentialToday’s focus: Programming with good styleWhat does this mean, and why does it matter?M-3Programming StyleA program is a document:Some of it is read by a computer.ALL of it is read by people.Donald Knuth: “literate programming”“Style” is a catch-all term for people-oriented programming.comments, spacing, indentation, namesclear, straightforward, well-organized code code qualityM-5Style in This CourseAlong the way, we suggest and sometimes require particular points of style in programs that are turned in for the on campus version of this course.It is common for employers to have style requirements that all programmers must follow.M-6/* Comments *//****************************************************** Program: Mi_To_Km* Purpose: Miles to Km conversion* Author: A. Hacker, 1/18/00 Sec. AF (Turing)*****************************************************//* Calculate volume of cylinder and ...* Inputs: radius, height, ...* Output: volume, ...* Assumes: radius, height nonnegative */.../* Tell user it’s negative. */Comment block at front of programComment block per major sectionSmall ones throughout M-7Required Comments (1)1. Heading comment at the beginning of each fileBrief explanation of what’s in the file2. Function heading commentsDescribe what the function doesMust explain (define) all parameters and resultShould never have to read function body to understand how to call itM-2M-8Required Comments (2)3. Variable declaration commentsDescribe information contained in the variableNot needed for trivial variables if their usage is obvious (loop indices,etc.) Should never have to read code that uses a variable to figure out what’s in it4. Statement commentsHigher-level summary of what the following group of statements does (as needed)Say what, not howMost individual statements won’t need commentsM-9Statement CommentsSay why, don’t paraphrase the code:NO: /* subtract one from sheep */sheep = sheep - 1; YES: /* account for the sheep that the big bad wolf just ate.*/sheep = sheep - 1;M-1 0SpacesUse blank lines to separate major sections.Vertically align like things:x= 5 ;yPrime= 7 ;z_axis = 4.3;Leave space around operators:No: y=slope*x+intercept; Yes: y = slope * x + intercept ;Use parentheses for emphasis, tooYes: y = (slope * x) + intercept ;M-1 1IndentationLike an outline, indent subordinate partsFunctionsIndent function bodyif statementsIndent what's done on trueIndent what's done on false (else)while and for loopsIndent loop bodySeveral styles are possibleBe clear, be consistentM-1 2Identifiers (Review)Identifiers name variables and other thingsLetters, digits, and underscores ( _ )Can’t begin with a digitNot a reserved word like double, return“Case-sensitive” VAR, Var, var, vAr are all differentUsing all CAPITAL letters is legal...but usually reserved for #defineconstantsM-1 3What’s in a Name?Extremely valuable documentation.Microsoft Excel has over 65,000 variables.How long is just right?mmphmiles_per_houraverage_miles_per_hour_that_the_red_car_wentAvoid similar names: mph vs. Mph vs. mqhM-3M-1 4Suggestions for NamesVariables and value-returning functions:Noun phrase describing information in variable or value returned by functionVoid functions:Verb phrase describing action performed when function is calledM-1 5More ExamplesOKrectangleWidth, rectangle_Width, rectangle_width, length_10_RectangleIllegal10TimesLength, My Variable, intLegal, but bad stylea1, I, O, xggh0sxx89s, rectangleWidth and rectanglewidth orrectangle_widthM-1 6ClarityDo “obvious” things the obvious wayNo: x = (y = x) + 1 ;Yes: y = x ;x = x + 1;Don’t be tricky, cute, or clever without GOOD reason. If so, comment it!M-1 8Centralize changesNo "magic numbers" (unexplained constants)use good names insteadAvoid typing errorsAvoid accidental assignments to constantsUsing #define is Good Style#define PI 3.14... PI = 17.2 ; syntax errordouble pi ;...pi = 3.14 ; ...pi = 17.2 ;M-2 0Many small points;Big cumulative effect...#include<stdio.h>int main(void){double v1,v2,v3,v4,v5;printf("Enter"" a number of miles per hour:");scanf("%lf",&v1);v5=v1*1.46666667;printf("%f miles per hour is"" equal to %f feet per second.\n",v1,v5); return 0;}M-2 1Style Summary:Clarity is Job #1DOUse plenty of comments - but not too manyUse white spaceUse indentationChoose descriptive namesUse named constantsDON’Tbe terse, tricky place speed above correctness, simplicityuse “magic
View Full Document