Java Style to Avoid

This page contains a list of various things I've encountered in students' programs this semester that might better be avoided. Expect it to expand from time to time.

* String constructors are seldom necessary.
* Boolean values need not be compared to true or false.
* Boolean variables may be assigned from arbitrary boolean expressions.
* Throws clauses aren't intended just to shut up the Java compiler.
* Be specific about exceptions.
* Don't leave commented-out regions of code.


String constructors are seldom necessary. Write

    String aString = "foo";
not
    String aString = new String ("foo");   // BAD


Boolean values need not be compared to true or false. Rather than writing

    if (isRound == true and isFilled == false)  // BAD
        ...
write
    if (isRound and not isFilled)
        ...
Of course, to make this work, you should choose names for things that contain or return booleans that suggest that they are boolean. For example, names like isRound, hasNext, amProcessing clearly suggest that their values are boolean.


Boolean variables may be assigned from arbitrary boolean expressions. Rather than writing

    if (not isFilled)             // BAD
        isOutline = true;
    else
        isOutline = false;
simply write
    isOutline = not isFilled;


Throws clauses aren't intended just to shut up the Java compiler. Unless you are writing a throw-away piece of code to try out something, avoid things like:

     public static void main (String[] args) throws IOException // BAD
If javac was complaining before you did this, it means that something in your code might crash the program by throwing IOException. Decide what you want to do in that case and put in a try...catch block.


Be specific about exceptions. In most cases, it is unwise to write

     try {
        doSomething ();
     } catch (Exception e) {     // BAD
        saySomething ();
     }
This will catch all exceptions, including things like NullPointerException, which is more often a programming error rather than an expected result of user errors. Try to narrow things down.


Don't leave commented-out regions of code. There is nothing more ugly (or difficult to read) than sections of program text that look like this:

     foo (x, y);
 //  foo (0, 0);
 //    if (x > y) {
 //        ...
 //   }
     return null;
Clean them up before you submit. In fact, don't have them there in the first place. With version control, you have all your old versions of code around in the repository, should you ever need to restore them.


[CS61B Home Page]

Page was last modified on Tue Oct 7 20:09:02 2008.
Address comments and questions to cs61b@imail.eecs.berkeley.edu