Coding Conventions

Coding conventions are important in this course because they make your code more readable, quicker to develop, and easier to grade. The bigger the project, the more benefit software conventions will have on development time.

In the real world, good software conventions are valued because the code is easier to maintain. Sun Microsystems, who created the Java language, found:

  • 40% to 80% of the lifetime cost of a piece of software goes to maintenance.
  • Most software is maintained by people other than the original author.
  • Coding conventions improve readability, allowing engineers to understand the code quickly and thoroughly.

Good coding conventions also allow you to revisit your own software months, maybe years later and quickly pick up where you left off.

Naming Conventions

  • Variable Names
    • Use full English descriptions for names. Avoid using abbreviations. Use names like firstName, lastName, middleInitial instead of fName, lName, and mInitial.
    • Avoid overly long names (greater than 15 characters). For example, theLengthOfTheField should be shortened to fieldLength.
    • Avoid names that are very similar or differ only in case. The names product, products, and Product are too similar and might get confused in the program.
  • Constant Names
    • Use ALL_UPPER_CASE for constants separating words with underline characters. For example, use TAX_RATE rather than taxRate or TAXRATE.
    • Avoid using “magic” numbers. These are numbers that have a special meaning in your code, like the number of cards in a hand. Give the number a meaningful constant name like final int CARD_HAND = 5; .
  • Method Names
    • Use names that are meaningful and describe the purpose of the method. For example, if you are writing a parser that returns a token, then parseToken() is a valid name.
    • Start each method with a lowercase letter and starting each subsequent word with an uppercase letter, like isAlphaChar() .
    • Use getter and setter methods to set and get private field values. For example, getBalance() returns the balance value and setBalance(value) sets the balance value.
    • If the method returns a boolean, use is and has prefixes in the name. For example, isOverdrawn() and hasCreditLeft() describes the truth values. Avoid using not in the method name, like isNotOverdrawn(). Instead, use ! isOverdrawn() in the program when this logic is required.

Commenting

Every program, no matter how small, should have file header comments to document the purpose, author, and version. Commenting should be done as you code, and not left as an afterthought.

  • File header comments
    • The first line has a forward slash followed by two asterisks (/**). This is a javadoc convention.
    • The second line has a description of the class and its purpose.
    • There is an @author line with your full name.
    • There is a @since line with the file’s creation date.
    • The final comment delimiter (*/) is on its own line.
        /**
         *  This program reads from a text file, counts the number of each letter in the alphabet,
         *  then prints out a frequency chart.
         *
         *  @author  Mr Greenstein
         *  @since   August 30, 2017
         */
                
  • Method comments
    • Method comments are indented the same distance as the method itself.
    • The first line has a forward slash followed by two asterisks (/**). This is a javadoc convention.
    • The second line has a description of the method and its purpose.
    • The @param and @return annotations are used as needed.
    • The final comment delimiter (*/) is on its own line.
        /**
         *  This method computes the monthly payment.
         *
         *  @param numYears  Number of years
         *  @param interest  Yearly interest rate
         *  @return   The monthly payment
         */
        public double monthlyPayment(int numYears, double interest) { ...
                
  • Single-line comments start with a double forward slash (//). They are preceded by a blank line and the comment is indented the same distance as the code around it.
        System.out.println();
   
        // Start with the letter 'A'
        lineChar = 'A';
        out.printf("\nFrequency of letters in file %s\n\n", inFileName);
   
        // Print out each line of letter frequency
        for (int i = 0; i < 26; i++) {
        ...
                
  • Trailing comments are to be used sparingly. One good use is for variables.
        int maxRows = 1000/20;  // maximum number of rows
        int maxCols = 11;       // maximum number of coloumns
                

Formatting

  • Indent 4 spaces for each level of control structure. Avoid using tabs because they look different on different computers and with different editors. For example:
        public void Run() {
            for (int i = 0; i < index; i++) {
                if (hasNext(i)) {
                     j = i + 'a';
                
  • Use blank lines to improve readability of code. For example, leave a blank line before single-line comments. It is also good to leave a space between logical “chunks” of 3 to 7 lines of code. For example:
        public Status Play() {
      
          // zero out turn counter
          count = 0;
          Status stat = new Status();
          
          // Place the pieces randomly on the board
          // and make them all alive
          InitializeBoard();
          s1.alive = d1.alive = j1.alive = true;
          
          Scanner keyboard = new Scanner(System.in);
          
          // 1 = slider1, 2 = diag1, 3 = jumper1
          int turn = 1;
          ...
                
  • Avoid lines longer than 80 characters. Break after a comma or before an operator. Align the new line with the beginning of the expression of the previous line. For example:
        public void student(String aName, int anAge, int aGrade, double anAverage, boolean aMale,
                            String address, String phone)
                

       and

            double average = (grade1 + grade2 + grade3 + grade4 + grade5 + grade6 + grade7 + grade8
                               + grade9) / 5.0;
                

Importing

  • Import statements come at the beginning of the file above the comments.
  • Every imported class must be spelled out. For example:
            import java.util.Scanner;
            import java.util.ArrayList;
            import java.io.File;
            import javax.swing.JFrame;
            import javax.swing.JPanel;
                
  • Do not use wildcard characters for imported classes. For example:
            import java.awt.*;          // Avoid this!
              
            import java.awt.Color;      // Do this instead
            import java.awt.Graphics;
              ...