Computer Science

Course Coding Standards


EXAMPLE CODE TO CONSIDER
Probable
Grade
    Notes
the excellent! MovingSpecsClient.java 100% Adheres to all coding standards AND...
  • documentation is helpful & includes short notes explaining out of the ordinary design decisions and apparent contradictions (press & click thing!)
  • good use of white space!
  • instructions to the user are eye catching!
  • window has been sized to create a pleasing visual
the good Ch2Client.java 90 - 95 % Adheres to all coding standards BUT ... misses the spirit of them. Even class name is not helpful.
Probably won't lose all available points but... definitely some.
and the ugly BadClient.java ??? (don't miss the TABS)
  1. 257 - Some changes made to HW#1, 1) will be part of our additional 257 coding standards.
    1. Use only Scanner for input.
      Do not use BufferedReader & FileReader.
    2. Use only printf in the appropriate ways.
      (Could be from System.out or a constructed PrintStream)
      Do not use PrintWriter, BufferedWriter,FileWriter
    3. Do not use break; or return; to exit loops or if-statements. (This repeats 11a below!))
      Instead develop and use boolean expressions to exit them. Methods should have as few exit points as possible (preferably only one).
    4. Follow all coding standards discussed below. Where unclear, discuss with me at least 24hrs ahead of any submission.

  1. Compilation & Interpretation of Code
    1. Code should compile on the lab machines. If it does not compile (DNC) on the lab machines, code will be given no credit. And I will not spend long looking for the problem.
    2. Code should compile on the lab machines with no warnings or messages.
    3. Code which has run-time errors on the lab machines should not be submitted. If it cannot be avoided, there should be documentation inside the source describing what you think the problem might be and what you've tried to do to correct it. This documentation should be located near the problem.
      Since the most common of these will be the dreaded NullPointerException, it will be especially important to learn what these are about and how to avoid them.
  2. Documentation
    1. Name your class that has the method "main" in it, with "Client" as part of the class name. So.. for example,
      • RandomClient.java
      • Statistical_Client.java
      • MouserClient.java
      • RedHouseClient.java
      • Client_RandomCircles.java
      • Client_RandomCircles.java
      • etc.
    2. For citation, all submitted files, regardless of size, will at the top contain lines which specify Programmer, Date, Homework or Laboratory assignment to which it pertains.
    3. For citation, all submitted files, regardless of size, will at the top include a brief description of "big picture" workings of your code. Write this to yourself so that if you were to pick up your code six months from now you would be able to quickly modify it or scavenge workable parts of it for another program. You don't want to start from scratch wondering how it does what it does, nor do you want picky implementation details. You want an overview with only enough detail to get you started.
    4. NOTE, the homework or laboratory number given should match the one used for that particular assignment on the course web pages rather than any private system of your own.

      Example,

                       // Casey Jones 
                       // September 8, 2044
                       // Homework #1:  Problem 5 - p.59 (2.7.4)
                       // Each mouse press draws a filled 20x20 square. 
                       // Each mouse release leaves a frame of the last square.
                       
  3. Formatting & Indentation
    1. Never use any column beyond 80.
      Why? Code which "wraps" is harder to read & understand when viewing (or printing!). Your poor instructor will be doing this A LOT. Column 80 is safe for all reasonably readable font sizes.
    2. Do no use tabs.
    3. For each "inner" scope, indentation should be exactly 2 spaces.
    4. In-line comments must begin in same column and above code they describe.

      Right
      // construct a square and provide instructions for user
      new FramedRect( 200, 200,  50, 50, canvas);
      new Text("Clicking makes things happen...", 20, 20, canvas);
                  
      Wrong
      // construct a square and provide instructions for user
        new FramedRect( 200, 200,  50, 50, canvas);
        new Text("Clicking makes things happen...", 20, 20, canvas);
                  
      Wrong
        // construct a square and provide instructions for user
      new FramedRect( 200, 200,  50, 50, canvas);
      new Text("Clicking makes things happen...", 20, 20, canvas);
                  
      Wrong
      new FramedRect( 200, 200,  50, 50, canvas);
      new Text("Clicking makes things happen...", 20, 20, canvas);
      // construct a square and provide instructions for user
                  

    5. Off-to-side comments must all begin in same column throughout source file.

      Right
      new FilledRect(55,50,50,5,canvas);      // left eyepiece of glasses
      new FramedOval( 50,50,60,50,canvas);
      new FramedOval( 51,51,58,48,canvas);
      
      new FilledRect(125,50,50,5,canvas);     // right eyepiece 
      new FramedOval(120,50,60,50,canvas);
      new FramedOval(121,51,58,48,canvas);
      
      new FilledRect(105,70,20,5,canvas);     // nose bridge
              
      Comments are where they should be AND ...
      • blank lines between logically related sections of code
        we will call this good use of "white space"
      • comments are meaningful, easy to read, NOT repetitive
      Wrong
      new FilledRect(55, 50, 50, 5, canvas);      // top of left eye
      new FramedOval( 50,50,60,50, canvas);   // oval of left eye -- outter frame
      new FramedOval( 51,51,58,48, canvas);//  oval for the left eye -- inner frame
      new FilledRect(125,50,50,5,canvas);  // top of right eye
      new FramedOval(120,50,60,50,canvas);  // oval1 of right eye
      new FramedOval(121,51,58,48,canvas);  // oval2 of right eye
      new FilledRect(105,70,20,5,canvas);// the bridge of glasses
              
      Wrong
      new FilledRect(  55,50, 50,  5,canvas);    // left eye -top bar
      new FramedOval(  50,50, 60, 50,canvas);    // left eye -bigger oval
      new FramedOval(  51,51, 58, 48,canvas);    // left eye -inside oval
      
      new FilledRect(125,50, 50,5,canvas);   // right eye -top bar
      new FramedOval(120,50, 60,50,canvas);  // right eye -bigger oval
      new FramedOval(121,51, 58,48,canvas);  // right eye -inside oval
      
      new FilledRect(105,70,20,5,canvas);           // glasses bridge center
              

    6. Always leave at least one space between comment delimiter and the comment itself.

      Right
      // Casey Jones 
                  
      Wrong
      //Casey Jones 
                  

    7. Make good use of 'white space'.

     

  4. Delete unused code.

     

  5. Variables, Names, & Identifiers
    1. Variable names and method names begin with lowercase letters. Those that read as multiple words are run together, with each successive word capitalized. Examples are redSquare and upperLeftCorner.
    2. Class identifiers begin with uppercase letters. Class names that read as multiple words are run together, with each successive word capitalized. Examples are MovingSpecsClient and FunnyFace. No class should be named with the word 'class' as part of it's name.
    3. All variables, method, and function names and identifiers should be carefully named and as meaningful as possible.
    4. Named Constants are to be all uppercase with underscores to separate words in them.
      For example:
      private static final int SUN_CORNER_X = 25;
    5. Instance variables should not be used when local variables will do. Determining the proper place for variable declaration is usually obvious. A variable used by more than one method is a good candidate for an instance variable. Sometimes it is more subtle. For example it is often more efficient to declare a generating object (ie, RandomIntGenerator) only once although it appears to be used only in one mouse event handling method.

      paraphrasing Ch8, p.219 of your text...

      General Guidelines:
      • Instance Variable - Should be used if a value is necessary as part of an object's STATE.
      • Formal Parameter - Should be used if a value is somehow useful but only in context and the client needs to be able to specify it.
      • Local Variable - Should be used if a value can be initialized locally and that value is not necessary for later method calls.

      The expanded reasoning on these guidelines can be found on the bottom half of p.219 of your text.

  6. Comments Required
    1. Every statment must be documented. However, you do not need to give every executable line it's own unique line of documentation. Good documentation requires some thought. It also takes a while to get used to doing it well and often. For some excellent examples of good documentation, look at what your textbook provides. This is the kind of documentation that actually helps you read the source code more easily. It does not repeat the code in English, but rather explains its purpose.

      For example, the below is an excellent example of documentation. One line of documentation explains several statements. And does it well!

          // construct three dice and directions for rolling them
          die1 = new FramedRect(canvas.getWidth()/4,   canvas.getHeight()/5, 50, 50, canvas);
          die2 = new FramedRect(canvas.getWidth()/2,   canvas.getHeight()/5, 50, 50, canvas);
          die3 = new FramedRect(canvas.getWidth()*3/4, canvas.getHeight()/5, 50, 50, canvas);
          msg  = new Text("Click to roll dice", 20, 20, canvas);
                      
    2. Comments should be meaningful. They should explain either what the programmer is doing or why it's being done. They should not simply echo the code as in the following examples.

      Pay attention to what you are doing. It is possible that some sections of your source code are 'self-documenting'. This is likely when you have been thoughtful about your variable names.

      Example - bad because it describes syntax of code:

              private FilledOval moon;        // declare variables
              private FilledOval shadow;
              private FilledRect nightsky;
              private Text instructions;
              

      Example - bad because it repeats code & adds no extra meaning:

              private FilledOval moon;        // filled oval that represents the moon
              
  7. Style Guidelines for Control Structures (if-statements, loops, etc)
    1. Boolean statements can & should be used in assignments where appropriate.
      
      boxGrabbed = box.contains(p);
                   
      is much better than the following equivalent but awkward code.
                           if ( box.contains(p) )
                             boxGrabbed = true;
                           else
                             boxGrabbed = false;
                   
    2. Don't use true or false in conditions.
      
      if (box.contains(p))
         new FilledOval(50,50,50,50,canvas);
      
                   
      is much better than the following equivalent but awkward code.
      
                           if ( box.contains(p) == true )
                             new FilledOval(50,50,50,50,canvas);
                   
      and same for loops
      
      while ( !done ) {
        . . . 
      }
                   
      is much better than the following equivalent but awkward code.
                           while ( done == false ) {
                             . . . 
                           }
                   
    3. Resist the temptation to comment on the language. A comment about a while loop saying that it is a while loop doesn't add any information. However saying that the loop will continue creating smaller inner circles until a minimum radius is reached is VERY HELPFUL. It comments on the problem. Great!
       
      
      // Make inner circles as long as radius is big enough
      while (r > 20){
        . . . 
      }
                   
      is much better than the following equivalent but repetitive documentation.
                           // while loop for circles
                           while (r > 20){
                             . . . 
                           }
                   

    4. Find helpful variable names and set up constant variables with helpful names rather than hard coding values. Compare the two examples below and decide which is more readable. (Hint: I find the first waaaaay superior...)
      
      while (radius > MINIMUM_RADIUS){
        . . . 
      }
                   
      is much better than the following equivalent but ambiguous code.
                           while (r > 20){
                             . . . 
                           }
                   

    5. Do not hard-code array sizes when going through loop values.
      for (int i=0; i < randomOvals.length; i++){
        randomOvals[i].setColor(Color.RED);
        . . . 
      } 
      -- or --
      for (FilledOval nextOval:randomOvals){
        nextOval.setColor(Color.RED);
        . . . 
      }
                   
      is much better than either of the following (probably) equivalent but less-robust code fragments.
                           for (int i=0; i < NUM_OVALS; i++){
                             randomOvals[i].setColor(Color.RED);
                             . . . 
                           }
                 
        
                           for (int i=0; i < 10; i++){
                             randomOvals[i].setColor(Color.RED);
                             . . . 
                           }
                   
  8. User Communication

    Unless assigment specifies otherwise, you must prompt user for input.

    1. Give user a very brief idea of what kind of code is running.
          (ie, integer sorting, base conversion, spinning cube, simulation of stock market, etc.)
    2. Inform user type of input expected.
    3. Inform user of any ranges outside of which input is invalid.
          (ie, maximum's, minimum's, etc.)
    4. Inform user of any other hard-coded values or assumptions.
          (ie, If no input entered for point, default is origin (0,0) )
  9. Error Checking

    Unless assigment specifies otherwise, you must perform error checking.

  10. Constructor and Method Parameters

    When passing parameters, all should be used in the method in the most 'reasonable' and 'intuitive' way.

  11. Transparency & Readability
    1. No "goto" or equivalent unconditional branching will be allowed in any code submitted for grading which is not using assembly for source. This includes "exit" and "break" statements. The only exception is the "break" statements which are required to properly terminate "switch" cases.
    2. A method or function should have as few 'entry' and 'exit' points as possible. These should logically occur at begining and ending of the method/function scope.