Share this page 

Easily remove my debugging codeTag(s): Language


Unlike a C/C++ compiler, there is no Java compiler directive to exclude certain source code parts from compilation. By making the release version of a class smaller, the loading process will be a little bit faster.

Without editing the source to remove the debugging codes, you can rely on the simple optimization that the Java compiler always do. If a if expression is always false, the code in the if statement will not be included in the compilation. Not only the resulting class will be smaller, but the execution time will be a little faster too by not making unnecessary test.

The technique is simple. In the development environment, you have a class called Debug.

public class Debug {
  private Debug() {}
  public static final boolean RELEASE = true;
}
In your source, when you need some debugging codes, you included them in a if statement like
if (Debug.RELEASE) {
   System.out.println("The value of i is " + i);
}
During compilation, since Debug.RELEASE is always true, the code will be present.

In the production environment, the Debug class looks like this:

public class Debug {
  private Debug() {}
  public static final boolean RELEASE = false;
}
When compiling in that environment, the debugging code will be absent from the class file since Debug.RELEASE is always false.