Java Style Guidelines for CS112

This document contains a summary of the most important recommendations/requirements for Java style, mostly concerned with layout of code and comments, and with the choice of good names. These have been derived by my own experience, those of the other Java instructors at BU, and a brief survey of online resources.

These recommendations are consistent with almost all Java style recommendations in the literature, and are followed in spirit by almost all Java programmers. You should use them unless you are specifically required to to do otherwise by a future employer or instructor, or you have some better idea that you can defend. They are designed to improve code readability, on the premises that far more human time is spent reading code than writing it, that far more human time is spent modifying existing code than writing entire programs from scratch, that far more code is written by groups of people than by single individuals. In particular, following these rules will make it easier for the grader to grade your work and the instructors to assist you if you are having difficulty. They will also help you think more clearly about your code!

Your development environment may have an auto-format feature which departs from these recommendations, and that is ok. Any reasonable variation from these standards, motivated by your due consideration of the reasons given below, will surely be acceptable, but please consult the TF or grader if you have concerns or questions.

Naming

Choose your names carefully. As part of program documentation, names must clearly indicate both the kind of thing being named and its role in the program. Whenever possible, write short, obvious names for very local contexts (i.e., a for loop counter could be called i) and longer names for bigger contexts (examples to follow). Avoid cryptic abbreviations (e.g.,use incrementEventCount() rather than incEvCnt()). Avoid choosing similar names for different things, e.g., index, indx, index2; or, on the other hand, similar names for very different things (example: if keys[] is a array of strings, then don't use key for an integer for loop counter).

Indentation and Whitespace

The placement of syntax on the page is one of the most important aspects of style and readability, and has three aspects: horizontal placement is achieved by (i) using spaces or tab stops to indent lines of code and other similar items (such as variables in a series of declarations), (ii) for inserting "oxygen" around operators and punctuation, and vertical placement is achieved by (iii) inserting blank lines to separate classes, members of classes, and regions of code with various purposes. Don't worry about using up too much space in the file, blank lines are usually just one or two characters!

The usual standard for indentation is to

Example:

class SomeClass{
    int someField; 

    double anotherField; 
    public SomeClass(){    // Constructor
        someField=1;

        anotherField = 3.14; // Initialize all fields
    }  
    int someMethod(int n,float m){
        int localVariable=0;      // Must initialize local variables
	    float anotherLocalVariable=1;    // This one too
	    localVariable=n-2;
	    anotherLocalVariable=localVariable+m*3; 
	    for(int i=0;i<someField;++i) {
	        localVariable=localVariable*2;
		localVariable=localVariable-someField;
        }
        return localVariable+n;
    }
}
   

This example is not in fact very readable, as it it hard to parse the structure of the individual lines; the usual standard for increasing readability of each line is:

Superfluous parentheses can also help to emphasize the structure of expressions (but not too many nested parentheses). This example, should thus be written as:

class SomeClass {
    int    someField; 

    double anotherField; 
    public SomeClass() {                       // Constructor
        someField     = 1;           
        another Field = 3.14;                  // Some people line up a series of initializations too.  
    }  
    int someMethod(int n, float m) {
        int   localVariable        = 0;        // Must initialize local variables
        float anotherLocalVariable = 1;    // This one too
	localVariable = (n - 2);
        anotherLocalVariable = localVariable + (m * 3); 
	for (int i = 0; i < someField; ++i) {
	    localVariable = localVariable * 2;
	    localVariable = localVariable - someField;
        }
        return (localVariable + n);
    }
}
 

Still too crowded! For vertical arrangement, simply

class SomeClass {

    int    someField;
    double anotherField; 
   
    public SomeClass() {                  // Constructor
        someField    = 1;
        anotherField = 3.14;              // Some people line up a series of initializations too. 
    }
     
    int someMethod(int n, float m) {
   
        int   localVariable        = 0;   // Sometimes too much lining up looks too fussy, so
        float anotherLocalVariable = 1;   // it is a matter of taste.
	  
        localVariable = (n - 2);
        anotherLocalVariable = localVariable + (m * 3); 
	  
        for(int i = 0; i < someField; ++i) {
	    localVariable = localVariable * 2;
	    localVariable = localVariable - someField;
        }
	  
        return (localVariable + n);
   }
}
Three or four blank lines should be used to separate class and interface definitions, when they occur in the same file.

Curly Braces

Curly braces delimit the bodies of classes, methods, and loops. There are two standard formats for braces, the first being illustrated above:

The second format, which is also widely used, and recommended for class and method definitions only, is to put each brace on a new line, and line them up vertically; the previous code in this format would look like this:

class SomeClass 
{
    int    someField;
    double anotherField; 
   
    public SomeClass()     
    {
        someField = 1;
        anotherField = 3.14; 
    }
     
    int someMethod(int n, float m) 
    {   
        int   localVariable = 0; 
        float anotherLocalVariable = 1;
	  
        localVariable = (n - 2);
        anotherLocalVariable = localVariable + (m * 3); 
	  
        for (int i = 0; i < someField; ++i) {
            localVariable = localVariable * 2;
            localVariable = localVariable - someField;
        }
	  
        return (localVariable + n);
    }
}
If you prefer this style, you can reset the default in some development environments, but then you must use it for every such block statement, including loops.

Comments

Comments should help the reader of your code to understand it. They may help YOU to understand it if you need to rework your code at some later point. In the case of a programming course, they also serve to convince the grader that you grasp the what, how and why of your code (as opposed to having hacked it into working). Like any other form of expression, it should not be flowery or repetitive. In particular observe the following guidelines.

The main point to observe in writing comments is that the clarify, rather than obscure, the purpose of the code; if you are writing a comment just to satisfy the grader, and not to explain, then you are probably doing the wrong thing. Good comments should help you to understand the code three months later, and help others to understand. Obvious and trivial comments just get in the way of understanding.

Miscellaneous

Keep Line Lengths Under 80 characters

On many machines and in many software packages, this is a standard line length. It makes it easier for others (like graders) to read and/or print your programs. If your parameter list for a method is too long to fit within 80 characters, then insert line breaks and use indentation to line up the parameters:

boolean calculateAverageDailyReturn(int customerID, double dailyBalanceForMonth[], double dailyInterestRate, double discountRate) 
{
should be rewritten as:
boolean calculateAverageDailyReturn(int    customerID, 
                                    double dailyBalanceForMonth[], 
									double dailyInterestRate, 
									double discountRate) 
{
If your println statement is too long, then you should break this up as well, using separate print statements:
System.out.println("The average daily return for customer " + customerID + " at the discount rate " + discountRate + " is " + A);
should be rewritten as:
System.out.print("The average daily return for customer " + customerID);
System.out.println(" at the discount rate " + discountRate + " is " + A);

Zen Programming

In general, a shorter program is better than a long program, and the most common mistake in style that most students make is to type WAY too many characters to solve a problem. They declare way too many variables, use duplicate or useless lines of code, don't think through the best way to arrange if-then-else statements, and so on. When you really understand something, then you can give a succinct, elegant presentation of just what is necessary to solve the problem. This shows you understand the essence of the problem and its solution and others will be able to understand it more easily. It is often more efficient as well! Here I will suggest some ways to eliminate the clutter and write better, shorter code.

Zen Boolean Expressions

The worst offenders by far are boolean expressions. Suppose you want to write a function which tests if a number if positive; here is the worst possible way to do it:

boolean isPositive(int n) {
      if( (n >= 0) == true ) {
          return true;
      }
      else
          return false;
}

The if statement is utterly unnecessary and redundant: any time you find yourself writing  if(....) return true; else return false; 
remember that the boolean expression is ALREADY true or false, so you can just write

boolean isPositive(int n) {
      return (n >= 0) == true ); 
}

But this is still too much!  The boolean expression (n >= 0) is evaluated to true or false, so checking if it is true is redundant, just write:

boolean isPositive(int n) {
      return (n >= 0); 
}
Any time you find yourself writing "... == true" just stop and delete that phrase---it's completely useless!

For negative tests, the same thing applied, but you should negate the whole expression with "!":

boolean isNegative(int n) {
      return (n >= 0) == false ); 
}

should be:

boolean isNegative(int n) {
      return !(n >= 0); 
}



Last modified by Wayne Snyder, 7/9/17