Reputation: 2079
Today I needed to ensure some code sections were guaranteed to be removed from production using just core Java (no AspectJ). After a bit of thought I realized I could do the following, other than being a complete abuse of the concept of contractual assertions can anyone suggest practical problems that could arise?
public class ProductionVerifier {
static boolean isTest;
static {
// This will set isTest to true if run with -ea, otherwise
// the following line will be removed and isTest will be false.
assert isTest=true;
}
public static final boolean TEST = isTest;
public static final void runOnlyIfInTest(Runnable runable) {
// javac will remove the following section if TEST == false
if (TEST) {
runable.run();
}
}
}
import static ProductionVerifier.*;
public class DemonstrationClass {
private static Runnable notForClient = new Runnable() {
public void run(){System.out.println("h4x0r");}
};
public static void main (String[] args) {
runOnlyIfInTest(notForClient);
}
}
My main initial concern was that the scope of the test code allowed it to be accessed from the production environment, but I think even if I wrapped each set of test statements in if (TEST) blocks there is probably some more fundamental issues with the pattern.
Edit: To conclude from the answer and linked question, there is a maintenance/design concern, which is that the enabling of assertions now changes the behavior of arbitrary bits of the system, and a technical issue, which is that the code in these statements is not actually removed from the class file as TEST is not a compile time constant. These issues could be solved by removing the assertions hack, although refactoring the code not to need ProductionVerifier
would be preferable.
Upvotes: 1
Views: 144
Reputation: 13008
If someone at the data center - for whatever reasons - enables assertions, your production is going to execute test code happily in the production environment: For example, if an administrator enables assertions to analyze another application, but he just picked the wrong one in his console. Or it's only possible to enable them globally. This just happens.
And you cannot really blame him: The basic problem is really that the connection between "assertions" and "conditionally execute production or test code" is not obvious.
Upvotes: 1