Jump to Real's How-to Main page

Easily remove my debugging code

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 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 {
  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 {
  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.

Another way is to simply close the out stream.
(System.out.println() will be present in your class but the output is disabled).

public class TestOut {
  public TestOut() { }

  public static void main(String s[]) {
    System.out.close();  // may want System.err.close() too
    for (int i=0; i < 100000; i++){ System.out.print(".");}
    }
 }

If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2005
[ home ]