Conditional Debugging without #ifdef
Problem
You want conditional compilation and Java doesn’t seem to provide it.
Solution
Use constants or command-line arguments, depending upon the goal.
Discussion
Some older languages such as C, PL/I, and C++ provide a feature known as conditional compilation. Conditional compilation means that parts of the program can be included or excluded at compile time based upon some condition. One thing it’s often used for is to include or exclude debugging print statements. When the program appears to be working, the developer is struck by a fit of hubris and removes all the error checking :-). A more common rationale is that the developer wants to make the finished program smaller -- a worthy goal -- or run faster by removing conditional statements.
Although Java lacks any explicit conditional compilation, there is a
kind of conditional compilation implicit in the language. All Java
compilers must do flow
analysis
to ensure that all paths to a
local variable’s usage pass through a statement that assigns it
a value first, that all returns from a function pass out via
someplace that provides a return value, and so on. Imagine what the
compiler will do when it finds an if statement
whose value is known to be false at compile
time. Why should it even generate code for the
condition? True, you say, but how can the results of an
if statement be known at compile time? Simple:
through final
boolean variables.
Further, if the value of the if condition ...