Merrimack

Dr. Lisa N. Michaud
Assistant Professor
Department of Computer Science

Summer 2013
Office Hours

any day: by appointment
9:30-1:30

Fall 2013 Courses

Introduction to IT

Programming Languages

 

Courses I Teach

Research

Personal

Women in CS

Home

CS Department

STYLE RULES FOR DR. MICHAUD'S COURSES
Last Updated: January 18, 2012

(the evils of goto)
from http://www.xkcd.com

The key to writing good computer programs comes in several pieces. Obviously, the correctness and execution of the program itself is an important part. However, a part which is equally important is the design and its documentation. We never write programs in a void; we are always part of a larger community, whether that community involves fellow students, professors in a programming course, or co-workers in a future job. Almost always, there will be someone who is going to have to read or make use of this program after you have completed it, and that someone is going to have to be brought up to speed on what you were trying to do, how you were doing it, and how your contribution should be used. That someone could be you; you would be surprised how hard it is to remember how a program was written only a few weeks after you put it aside!

DOCUMENTATION

Most (if not all) modern computer programming languages include some way to provide documentation alongside your program itself. This documentation is ignored by the computer, but any human reading your program will be thankful for it.

An excellent rule of thumb is:
Do not comment your code; code your comments.

In other words, the comments should be the first thing you put into a new file. Use them to lay out your approach in pseudo-code; you can then fill in the details with the actual program. A bonus to this approach is that you do not have to worry about adding comments 5 minutes before your assignment is due.

When you provide documentation for any program, you should keep the following factors in mind:

  • Audience: Who is going to need to read this program in the future? Just you? Your professor? Your classmates? Some unknown future programmer?
  • Precision: Once you have figured out what the audience of this piece is, determine what details this audience needs to have in order to understand your program. Do not be vague about anything this person would need to know about.
  • Correctness: Make certain that your documentation actually tells the truth about the program! If you make any changes to the program, update the documentation to fit. Always test any claim you make.
  • Completeness: Do not document only one part of your program, and then leave large parts of it undocumented. Make certain you cover everything that the audience needs to use it for, or might wonder about.

The primary vehicle for documenting a program is the comment, an aside within the program itself that is "invisible" to the computer. In this course, you must always provide the following comments at a minimum:

Header Comment: This comment occurs at the top of every source code file and every header file. Its minimum content is:
  • your name
  • the name of the file
  • (if the main source code file) the purpose of the program and what input it expects (from the keyboard or files) and what output it will produce (to screen or files)
  • (if a supporting file) the purpose/function of the class / data structure / constants defined in the file

Examples:

		//============================================================
		// Lisa Michaud
		// CSC 5555
		// Fall 2010
		//
		// HoopyFrood.java : A program to display to the user random
		// and witty quotes from the Hitchhiker's Guide to the Galaxy.
		// Requires no input, and outputs text to the screen.
		//============================================================
		
		//============================================================
		// Lisa Michaud
		// CSC 1111
		// Spring 2010
		// 
		// Towels.cpp,.h : Defining a class for the 'towel' object,
		// used in the HoopyFrood program to provide both protection and
		// shelter.
		//============================================================     
      

Function/Method Comment: At the beginning of each function or method you define, you must have a comment explaining the function with a minimum of the following:

  • the name of the function
  • the PRE condition, including: all expectations for values in any parameters sent to the function and any values in any data members to which the function has access, and the presence of any required input files
  • the POST condition, including: changes to the values of any of the above, any output to the screen, any output to any files, and any value returned (if any)
Example:
		
		//============================================================
		// IsEven()
		//
		// PRE: Parameter 'num' contains a value to be tested to see
		// if it is even.
		// POST: Returns true if 'num' is even; false otherwise.
		//============================================================
		

Internal Comments: Inside functions, you must comment both the declarations of variables and any major parts of a function that are not entirely self-explanatory. You do not need to comment every line, but comment sections of a function so that the reader can see what each part does.

As a guiding rule, do not merely repeat in English what the declaration says ("An integer") or what the code says ("Tests to see if it is equal to 42").  Tell the reader what the purpose of that bit of code is.

Example:

		int id;           // the ID number of a person in the DB
	  	int SSN;          // the person's social security number
		
		// determine if the person has guessed the correct number
		if ( number == 42 )
			cout << "YES!!"; 

Closing Braces: Always write a comment on the line of a closing brace. It is never a bad thing to know exactly what control structure is being closed by that brace; when there are many braces, it is useful to know which goes with which.

Example:

		while ( answer == 42 )
		{
			if ( a <= b )
			{
				for ( int i=0; i<3; i++ )
				{
					cout << i << endl;
				} // end for
			} // end if
		} // end while
		
INDENTATION AND OTHER WHITESPACE

While languages such as C++ and Java do not require you to indent your code, nor in fact to include any whitespace at all if you wish to smush all of your statements together on one line and never use the spacebar, the return key, or the tab key, it is a necessity for readability that you use all of these three keys in good amounts.

  • Blocks of code (in C-based languages, surrounded by curly brackets/braces) must always be indented a minimum of 3 spaces from the surrounding code.
  • Indentation must be consistent; code at the same level of nesting must have the same level of indentation, and indentation cannot change from block to block for no reason.
  • Other whitespace such as spaces between lines and between functions should be used as you see fit to space out your code and make it easier to follow.

See the example code above for illustrations of all three of these points.

VARIABLE AND FUNCTION NAMES

It goes without saying that variable names such as x and y are not very informative unless you are talking about coordinates, and that one-letter variables should not be used for many purposes other than as loop indices. Do not be stingy with the names you give to your variables, functions, and object classes. Do not be cryptic, either. Allow them to be descriptive. Even when you comment their declarations, a reader will best remember that identifier's purpose if the identifier is easy to read.

A very good rule of thumb is:

  • Functions do actions, and therefore should be verbs or phrases that act like verbs. For example:

    getDepth();
    findMaximum();
    switchValues();

  • Variables and classes contain information, and are therefore basically objects, and therefore should be named as nouns or phrases that act like nouns. For example:

    int max_number;
    float avg_weight;
    class MyState { };

  • Be consistent with your use of capitals, underscores, etc., following the conventions you are taught. These conventions include the following options that are dominant in C, C++, and Java:

    • all lower case, often employing underscores: user_name
      • often used for function/method parameters and local variables

    • mixed capitals, starting with an upper-case letter: GameState
      • often used for class names

    • camel case, starting with a lower-case letter: getCurrentLevel()
      • conventional for methods and functions in C-based languages
      • used also for data members of a class

    • all upper case, often employing underscores: MAX_STUDENTS
      • always reserved for constants
CLASS STRUCTURE

When defining your classes, keep in mind that abstraction is one of the keys to good design. Therefore, you must:

  • Keep data members private.
  • Only constants should be global.
  • Make public Get/Set functions (methods) to access or change their value.
  • If functions are only used within the class, make them private.

In C and C++, always place your class definition in a header file with the same name and the implementation of the functions for that class in a source file, also of the same name. In java, where there is only one file for a class definition, the file name must be the same as the class it defines.

FUNCTION STRUCTURE

A wise programmer once said: "A function should never be larger than one screen." Functions that stretch on for hundreds of lines are not following a modular structure; they must be broken down further into smaller functions. Screen sizes vary, but this general guideline helps give you a heads-up when a function is getting out of control.

CONTROL STRUCTURES

The cartoon at the top of this page makes fun of the use of GOTO, but the fact is that control structure abuse is a common and costly problem. Use the following rule of thumb:

The control structure itself must determine the flow of the program. This means that a loop's boolean expression should encompass all possibilities for continuing the loop or stopping. The use of a break, or a goto, should never jump out of a loop, or a branch (if/else). The only place "break" should be used in a C-like language is in switch/case, where it is necessary. It is never considered acceptable to use "goto," unless you do want to be eaten by a velociraptor.