A comment in my previous entry asks why statics can cause problems. Here is a quick example of a program that wants to handle a -verbose option:

public class Foo {
private static boolean m_verbose = false;
public static void main(String[] argv) {
if (/* argv contains -verbose */) {
m_verbose = true;
}
runProgram();
}

Now imagine you invoke your program twice in the same build file as follows:

<java classname="Foo" line="-verbose"/>
... and somewhere else
<java classname="Foo" />

You will probably wonder why the second invocation keeps being invoked in verbose mode…

The solution is of course:

<java fork="yes" classname="Foo" line="-verbose"/>
... and somewhere else
<java fork="yes" classname="Foo" />

If you forget to fork a new JVM, the static variables set in the previous invocations will not be reinitialized. The problem with the fork flag is that it creates a new JVM each time, which dramatically increases the time of your build.

Therefore, it is much cleaner to avoid static variables as a rule of thumb, for example by storing all your command line variables in a singleton class and make sure this singleton gets reinitialized each time your program is invoked.

Now, does this mean you should never use static methods/fields? Of course not. Actually, I like to use static methods as much as I can as long as they don’t modify static state, because const static methods decrease the coupling of your classes.

But this will be the subject of a future entry.