CIS 22 Data Structures - Some Notes on Programming Style


  1. The sole purpose of comments, indentation, and variable names are to aid the reader. These facilities should all be used to make your program more readable. In particular, beginning programmers place undue stress upon 'trivial' comments. My personal preference is to write code so as to minimize the need for comments. For example, the following code fragment
    	if (a < 60)
    		g = 'F';
    
    does not provide the reader with any clues as to what is being accomplished. Slightly better is the commented version.
    	
    	if (a < 60)		/* grade is 'F' if average is < 60 */
    		g = 'F';
    
    But why bother with the comment, when properly named variables provide the same information?
    	if (average < 60)
    		grade = 'F';
    
  2. Each function should have at minimum a comment at the beginning outlining its objective. Each non-trivial loop should have a comment at its beginning outlining the purpose of the loop, (together with an explanation of the terminating condition if not obvious). Each non-trivial conditional should have a comment at its beginning (and at each else) outlining the reason for the conditional.
  3. Use whatever style indentation you feel comfortable with. Unless I find something extremely offensive in your indentation style, I would rather you continue whatever style you are getting used to (rather than require you to switch to my preferred style). You may wish to look at C code in textbooks -- there is a fairly agreed-upon standard style of indentation for C. Use tabs, not spaces for your indentations.
  4. Blank lines can do wonders for your program -- before and after loops, multi-line comments, between functions, between declarations and executable portions of a function, ...
  5. Output should be readable on its own, without the aid of the source. Simply printing out a slew of numbers and strings is unacceptable -- the reader requires explanatory text for the output. For example, compare:
    		1 2 5 6
    		2 6 7 8	
    		1 2 5 6 7 8
    		2 6
    
    with:
    		set 1: 1 2 5 6
    		set 2: 2 6 7 8
    		set 1 union set 2: 1 2 5 6 7 8
    		set 1 intersect set 2: 2 6
    
  6. Since you are programming these projects to be graded, you have to convince me that the program works. As such, I often have to know what the input data was. Depending upon the project you might simply supply me u with the raw data file, or print the input as you read it in.
  7. Avoid 'magic values' in your program (e.g., array bounds, characters corresponding to menu responses); instead use #define's to make your code neater and more readable.