Compare Objects With Equals

Use equals() to compare object references; avoid comparing them with ==.
Here's an example of code that would violate this rule:  

class Foo {
 boolean bar(String a, String b) {
  return a == b;
 }
}


Position Litera ls First In Comparisons

Position literals first in String comparisons - that way if the String is null you won't get a NullPointerException, it'll just return false.
Here's an example of code that would violatethis rule:   

class Foo {
 boolean bar(String x) {
  return x.equals("2"); // should be "2".equals(x)
 }
}  


Close Resource

Ensure that resources (like Connection, Statement, and ResultSet objects) are always closed after use.
Here's an example of code that would violate this rule:   

public class Bar {
 public void foo() {
  Connection c = pool.getConnection();
  try {
    // do stuff
  } catch (SQLException ex) {
    // handle exception
  } finally {
    // oops, should close the connection using 'close'!
    // c.close();

  }
 }
}


Non Static Initializer

A nonstatic initializer block will be called any time a constructor is invoked (just prior to invoking the constructor). While this is a valid language construct, it is rarely used and is confusing.

Here's an example of code that would violate this rule:  
  
public class MyClass {
 // this block gets run before any call to a constructor
 {
  System.out.println("I am about to construct myself");
 }
}


Avoid Protected Field In Final Class

Do not use protected fields in final classes since they cannot be subclassed. Clarify your intent by using private or package access modifiers instead.
Here's an example of code that would violate this rule:   

public final class Bar {
 private int x;
 protected int y;  // Bar cannot be subclassed, so is y really
                           // private or package visible???
 Bar() {}
}


Avoid Synchronized At Method Level

Method level synchronization can backfire when new code is added to the method. Block-level synchronization helps to ensure that only the code that needs synchronization gets it.
Here's an example of code that would violate this rule:

public class Foo {
 // Try to avoid this
 synchronized void foo() {
 }
 // Prefer this:
 void bar() {
  synchronized(this) {
  }
 }
}


Use Notify All Instead Of Notify

Thread.notify() awakens a thread monitoring the object. If more than one thread is monitoring, then only one is chosen. The thread chosen is arbitrary; thus it's usually safer to call notifyAll() instead.
Here's an example of code that would violate this rule:   

public class Foo {
 void bar() {
  x.notify();
  // If many threads are monitoring x,
  // only one (and you won't know which) will be notified.
  // use instead:
  x.notifyAll();
 }

<<Previous Page  +  Next Page >>