15

I am doing a Java application, which will use swing user interface. It will ask user to specify some settings, by filling in forms, and then process them and generate some files in the ./output/ directory.

During development process, I'd like to output some technical information in console, using System.out.println() method.

Do I need to remove all these console outputs when I'll finish development?

If yes, what is the best way to display debug information during development process to easily remove it before production?

Maybe I should use only JUnit tests for debugging purposes? I've just started with it, so I have vague idea of ​​its capabilities.

4

2 Answers 2

20

If you're not going to use a specialised debugging framework it could be as easy as:

if (Debugger.isEnabled())
    Debugger.log("message here");

The Debugger class just encapsulates the println calls (like this):

public class Debugger{
    public static boolean isEnabled(){
        return true;
    }

    public static void log(Object o){
        System.out.println(o.toString());
    }
}

That way when you want to go to production, or you can modify the behavior of your debugging (or disable it) by changing one line in a class.

2
  • 1
    Thanks, I'll, probably, better try some debugging framework, as you mentioned. :) Aug 12, 2012 at 16:25
  • I tried this but it said non-static method Debugger cannot be accessed from static content
    – JFreeman
    Mar 28, 2018 at 8:10
9

A small improvement to the Debugger class to make the client a little cleaner:

public static void log(Object o){
    if(Debugger.isEnabled()) {
        System.out.println(o.toString());
    }           
}

Then the client side would need just one line:

Debugger.log("....")
1
  • 1
    This is not a better solution in my opinion. Often debug message strings need formatting and this takes CPU time even when debugging is disabled. Checking for debugging outside the call to log() saves that (the branch occurs anyway). Alternatively, you can have a log() method that wraps string formatting.
    – Yuval
    Oct 14, 2016 at 22:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.