views:

175

answers:

2

I am programming Android applications, and the best way here may or may not be the same as Java in general.

I simply want to be able to set a debug flag that will only execute certain portions of code when it's set to true––equiv to C++ setting a preprocessor #define DEBUG and using #ifdef DEBUG.

Is there an accepted or best way to accomplish this in Java?

Right now I'm just going to set a variable in my Application object, but I don't imagine this is the best way.

+2  A: 

That's the way I do it:

// in some.class.with.Constants
public static final boolean DEV_MODE = true;

// in some other class
import static some.class.with.Constants.DEV_MODE;

if(DEV_MODE){
    Log.d('sometag', 'somemessage');
}
alex
Nice! I didn't know you could import all the way down to a single constant! I was looking to avoid typing X.X.CONST every time. This, combined with the answer referenced in the comment on my question (http://stackoverflow.com/questions/1344270/java-preprocessor), which shows how an 'if' statement with a false constant in its condition gets excluded from the compilation, is exactly what I was looking for. Thanks!
stormin986
+2  A: 
if ( Debug.isDebuggerConnected() ) {
  // debug stuff
}
drawnonward
I like this, and I imagine I'll find it quite useful at times, but I like how the other approach omits the entire block from the compilation with a false constant in the 'if' statement.
stormin986
I use both methods and comment conditionals. Each has its place, although a real preprocessor would be best.
drawnonward