Reputation: 18918
In C++ if we do not want some statements to compile into code that ships like assert function calls, we control their compilation through #ifndef preprocessor directives.
How do we do this in Java?
I have some System.out.println() statements for debugging which I would like to remove for the final code.
one way is to make them execute conditionally under the affect of a boolean variable. Is there a better way of doing this?
As I have a java swing application I can turn off the System.out.println statements without affecting the output. What is the method of doing this?
Upvotes: 1
Views: 404
Reputation: 30828
For what you're doing, assertions may be the way to go. The assert
keyword was added to Java in version 1.4, and is conceptually similar to C++'s assert()
, which I see you're familiar with.
assert
statements in Java do nothing if they evaluate to true and yell at you otherwise, which is perfect for debugging. They also don't work by default, which means that the compiler will ignore them unless you explicitly tell it not to. The end result is a debugging tool that "evaporates" when you ship your production code.
Here's Sun's tutorial on Java assert
s.
Upvotes: 0
Reputation: 11216
In general (not only for your example), you can create multiple implementations of an interface, and change, which instance is used during execution. This is called polymorphism, the advantage over if/else is: you choose the implementation once, instead of every time it's used.
In Java, polymorphism does not result in performance overhead.
public interface MyInterface {
void trashTheCPU();
}
public class MyRealImpl implements MyInterface {
@Override
public void trashTheCPU() {
// actually trash the CPU with heavy tasks
}
}
public class MyEmptyImpl implements MyInterface {
@Override
public void trashTheCPU() {
// do nothing
}
}
// ... somewhere else:
MyInterface mi = null;
public void initEveryting() {
if(trashTheCPUconditionIsMet) {
mi = new MyRealImpl();
} else {
mi = new MyEmptyImpl();
}
}
Upvotes: 0
Reputation: 68268
Use AspectJ for those pieces of code which you want added or removed at compile time and compile without AspectJ when you don't want to use them.
Upvotes: 3
Reputation: 54005
Use logging. See log4j or commons logging.
Generally, each log entry has a severity level (like debug, info, warning, error) and you can configure which are printed from the application. You can print all of them for debug, but only some (e.g. info and higher) in production. The configuration is usually done with a single plain text file.
Logging frameworks can do more than that: Add more detail automatically (e.g. timestamp or thread ID), log to console, file and/or database, rotate files, and more.
Upvotes: 4