Brian Ziman's Java Code Conventions

Contents

Introduction Top

Programming students come from a diverse background and have been introduced to Java from a variety of sources. Unfortunately, many professors do not emphasize proper coding practices in their classes, and some text books, like the Deitel book, present a very poor example to their readers. This document attempts to present some of the essentials for good coding practices. Many of these practices were defined by Sun as the Java language was developed, and others come from years of professional experience. Some of the specifics may be different from place to place, but in general, you'll find that following these guidelines will make your code easier to read, both for you and your colleagues.

"Official" Code Conventions Top

For the first several years of its existence, the vast majority of professionally developed Java code was written by engineers at Sun Microsystems, the original inventors of the Java language. In an effort to provide consistency and readability, they developed a set of code conventions for their developers to use, and this style is largely emulated by the Java community. These conventions are documented on Oracle's web site, since Sun was acquired by Oracle. This is great reading if you have trouble sleeping, or suffer from OCD and can't help yourself. The easiest way to learn these conventions is to read a lot of source code. I recommend reading the code I post on Blackboard, as that uses the style that I like to see when I'm reading code.

Classroom Code Conventions Top

For our purposes, I will try to summarize the highlights of good coding practices, and include things that are important for students, that probably aren't covered in the official document on Oracle's web site.

  1. Naming Conventions Top

    In Java, we prefer to use mostly lower case for our names.

    Classes MUST begin with a capital letter, and nearly everything else begins with a lowercase letter.

    When naming most identifiers, we use what is called "Camel Case". Camel case refers to including capital letters in the middle of names at the beginning of each subsequent word. For example, if you had a field that indicated the day of the week, you might name it dayOfTheWeek. If you had an accessor that retrieved that field, you would call it getDayOfTheWeek(). Notice that when we added another word in front, we had to make the "D" capitalized.

    One exception is for constants, which are named using all capital letters, with words separated by underscores, for example, LIGHT_BLUE. There are two types of commonly used constants: one is any field declared static and final (static means that it is shared among all instances of a class, and final means that its value cannot be changed); the other is a value in an Enum class.

    The other exception is for package names, which should be in all lowercase, regardless of the number of words, for example, the Java package javax.management.modelmbean. You should note that this package contains a class called ModelMBean that uses camel case.

    A class typically represents a "thing", and it should be named with a noun. A good way to tell if a class is named well is to insert it into a sentence like "Where do I find a ________?" or "Could you toss me a ________?" It will be silly, but if the sentence makes sense, then you're probably okay.

    A method typically represents an "action", and should be named with a verb. For example, getName(), addScoop(), eraseHardDrive(), calculateResult. One exception is for methods that return a boolean. These methods should be named as a question. For example, hasNextInt(), isEmpty(), and so on.

    One final thing to note: when writing about Java code, I find that it is helpful to always add () to the name of a method, in order to distinguish it from a variable. All other differences can be inferred by the case of the name.

  2. Indentation and Spacing Top

    This is one of the areas that gets a lot of debate, but for my classes, it is best if you do it the way I describe it.

    It is very important to me that you do not mix tabs and spaces! In your editor, when you press the tab key to indent, sometimes it inserts spaces, and sometimes it inserts a single tab character (ASCII code 9, for those who care). You should configure your editor to insert several spaces when press the tab key, instead of a single tab character.

    Regardless of whether or not you use the tab key, each level of indentation in a Java program should be four spaces.

    In order not to waste screen space, you should put opening curly brackets, {, on the same line as the thing they're opening. Close curly brackets, }, will go on a line by themselves (with the occasional exception).

    Each time you type an open curly brace, {, the next line should be indented four spaces more than you indented on the previous line.

    Each time you want to type a close curly brace, }, first you should indent four spaces fewer than you indented on the previous line.

    In the absence of curly brackets, each line should be indented precisely the same amount as the line before it.

    As usual, there is an exception! Because everyone sets up the screens and editors differently, it is usually best to limit the length of lines in your code to fewer than 80 characters. If you have long lines, it can improve readability to break those lines up in logical places. Typically if you do this, the broken out sections should be indented extra, so that it is obvious they are a continuation of the previous line.

    Certain structures in Java can deal with multiple blocks, for example, if-else. In this case, you should put the continuation (such as "else") on the same line as the closing curly brace of the previous block.

    Example:

    // This line is not indented
    public class MyClass {
        public boolean beAGoodExample(int n) {
            for(int i = 0; i < n; i ++) {
                System.out.println("i = " + i + ", i * 100 = " + (i * 100) +
                                        ", i * i = " + (i * i));
            }
            if(n < 10) {
                return true;
            } else { // note that continuation goes between open and close braces
                return false;
            }
        }
    }
    

    You should also notice from the example above, that punctuation, such as a semicolon is followed by a space, and that operators, such as addition and assignment, are surrounded by a space before and after.

  3. Comments and Documentation Top

    It is exceedingly important that you document your code. Even though most of the programs in class our very simple, if you ever find yourself programming for a job, you'll often find that code requires a great deal of forethought and planning. You'll also find that when you inevitably have to go back months later and review a piece of code you wrote, you won't remember anything about the decisions you made or the planning that you did. Having your code documented can save you many hours of frustration in these situations. Likewise, when you inherit code written by someone else, it is always nice if they have left you hints on what they were thinking.

    There are three styles of comments in Java: block comments; single line comments; and JavaDoc style comments.

    Block comments are the traditional C-style multi-line comments that begin with a slash and a star (asterisk), and end with a star and a slash. I find that these comments are most useful for temporarily commenting out a block of code. Since I don't use block style comments within methods (and you shouldn't either), that is very convenient.

    Most comments found inside methods should be of the single line variety. A single line comment begins with two slashes, and continues to the end of the line. These are useful for explaining what variables are, or how an algorithm works. Basically any time you want to leave a note for yourself or another future reader of your code. If you aren't sure why something works the way it does, or if you've got a question about a design decision, leave yourself a comment for later.

    Finally, JavaDoc style comments are used before each class, method, and often fields, to produce external documentation for your software. When you are reading about java.util.Scanner on the Oracle web site, that API documentation was actually generated using a program called javadoc that reads JavaDoc style comments out of your source code, and uses them to produce HTML documentation. JavaDoc style comments are basically the same as block comments, except that it begins with a slash and two stars, and (typically) each subsequent line of the block comment begins with a star.

    A web search for "JavaDoc" will yield a great deal of useful information about what features are available, and how to generate HTML documentation for yourself.

    Example:

    /**
     * (JavaDoc style comment)
     * This class is an example on Java commenting style.
     * (notice that the stars are indented so that they line up.)
     */
    public class MyClass {
        /**
         * This is the JavaDoc for a method.
         * @param n is the number of iterations to perform.
         * @return true if n is less than 10, false otherwise.
         */
        public boolean beAGoodExample(int n) {
            // this loop does some arithmetic
            // and displays the results
            for(int i = 0; i < n; i ++) {
                System.out.println("i = " + i + ", i * 100 = " + (i * 100) +
                                        ", i * i = " + (i * i));
            }
            /* let's comment this block out
            if(n < 17) {
                return true;
            } else { // note that continuation goes between open and close braces
                return false;
            }
            */
            if(n < 10) {
                return true;
            } else { // note that continuation goes between open and close braces
                return false;
            }
        }
    }
    
  4. Scope Top

    When declaring variables, you should declare the variables as close to their point of usage as possible, instead of at the beginning of a method. In Java, there is a concept of "scope" which refers to the lifespan and accessibility of a variable. Generally, the scope of a variable is limited to the block in which it has been declared. You want to choose the narrowest scope possible for your declarations. Most of the time, you can initialize a variable at the same time as it's declared.

    Example:

    public class MyClass {
        /** 
         * Print out ten magic numbers and return true
         * if any were evenly divisible by 17.
         */
        public boolean beAGoodExample() {
            System.out.println("This is an example.");
            boolean result = false;
            for(int i = 0; i < 10; i++) {
                int x = 17 * i + 3;
                System.out.println("magic("+i+") = "+x);
                if(x % 17 == 0) result = true;
            }
            return result;
        }
    }
    

    Notice that the variable "result" is first used on the line with the if statement. But, since we need to be able to return the result, we cannot declare it inside the block. So immediately before the block is the closest viable location, and that is where it is declared. Notice that the variable "x" is only used inside the loop, and therefore it is declared there.

    You accomplish several goals by limiting scope. First, you put the variable as close to the action as possible, eliminating the need to hunt for the declaration of a variable that you're currently looking at. Second, it removes the variable and frees up the memory associated with it as soon as the variable is no longer needed. Finally, it helps prevent mistakes, because the compiler will detect if you're trying to use a variable that's no longer in scope, and it will prevent you from re-using a variable for multiple purposes, possibly (and accidentally) re-using an unintended old value.


Top | Home | Contact
Copyright © 2011 Brian Ziman
Updated: Friday, 28 January, 2011