No preprocessor in Java - If I would conditionally like verbose output for debug, what's the best way?

StackOverflow https://stackoverflow.com/questions/20686527

  •  19-09-2022
  •  | 
  •  

Question

So, in languages like C and C++ I could define a preprocessor directive and do conditional compilation like so:

#define DEBUG 1


#ifdef DEBUG
   cout << "Some Stuff, blah blah blah" << endl;
#endif

My goal is to do something similar, or roughly similar in Java that way I can do some debugging and just switch DEBUG on or off real quick for debug or release compilation. Is there anything anywhere close to this in java?? Maybe a

public static final String DEBUG = "YES"

I don't know....Is there anything anywhere close to this, what's my best strategy. Recommendations?

EDIT: I am hoping to avoid any custom libraries, because I am OCD.....lol

Was it helpful?

Solution

Java is very flexible in this case, plus there are many custom libraries enable you to do this(log4j).

As you dont want to use any of them, but still allow you to do it flexibly with out recompiling the code,

  1. Define a properties file (say custom.properties)

enabledebug=true

  1. Define a global property

     class Global {
    
         public static boolean DEBUGFLAG=false;
    }
    
  2. Define a method to read the property and the the flag value to global variable

    public void load() {
      Properties props = new Properties();
      FileInputStream fis = new FileInputStream("....custom.properties")
      props.load(fis);
      Global.DEBUGFLAG= Boolean.valueOf(props.get("enabledebug"));
    }
    
  3. Invoke load method from main method

  4. use the flag when ever you need to print verbose

    if(Global.DEBUGFLAG) {
    
     //print some thing
    }
    

OTHER TIPS

I use a boolean constant to do that...

public static final boolean VERBOSE = true;
.
.
.
if (VERBOSE) log("your message here");

When VERBOSE=false the compiler just ignores the IF sentence.

I usually do something like:

public static final bool FEATURE_SOMETHING = false

if (FEATURE_SOMETHING) {
   do something / instantiate other class etc.
}

If it's just logging you need, there are many Java logging APIs to choose from, including one built into Java itself. They aren't going to be as convenient as conditional code. But when your code is deployed you can switch on logging and get output, which you can't do with preprocessed code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top