In my previous post I wrote that Java 8 has a new, functional face – and a pretty one. Programming in a functional style is not a theoretical whim of computer scientists, is has immediate practical consequences. Thinking in terms of function composition produces shorter code that is easier to read and, more importantly, more robust.
In this article I will show a few functional little tricks that yield significant benefits.
Efficient assertions
Assertions are a powerful way to create self-verifying code. A programmer who routinely uses assertions writes better code simply because he has to think twice about the invariants of a program.
However, assertions do incur a performance penalty if the asserted expression is complex. This can be addressed in Java 8 by using lazy evaluation via an anonymous function returning a boolean:
instead of using the classic assert keyword:
To do this trick we need a class Assert that contains a method must() which does all the work. Firstly, Assert should be able to detect that assertions are turned on:
public static final boolean ON = true;
private static boolean isEnabled = false;
static {
assert isEnabled = true; // side effects intended
}
public static boolean enabled() { return isEnabled; }
The ON flag allows the programmer to remove the asserting code anywhere in his program by leveraging the optimizing capabilities of the Java compiler (the so-called conditional compilation idiom in Java). The isEnabled internal flag is set to true whenever assertions are globally turned on. The enabled() method allows read-only access to isEnabled from anywhere in the program.
The code for the must() method is deceptively trivial:
public static void must(Supplier<Boolean> assertion) {
if (ON) {
if (enabled()) {
assert assertion.get();
}
}
}
The ON flag eliminates the method altogether when false and the call to enabled() makes sure the evaluation of assertion takes placed only when assertions are turned on. The Appendix contains the full code for the Assert class.