I see often classic constructs like this:
if (LOG.isLoggable(Level.FINER)) {
LOG.finer("The driver of the car is '"+ car.getDriver().getName() +"'.");
}
Assuming the car has no driver, the getDriver()
returns null
.
The implementation of LOG.finer
can be found here: http://developer.classpath.org/doc/java/util/logging/Logger-source.html#line.971
Then:
getName()
can not be executed onnull
so an NPE will be thrown. Only under one special circumstance: I must have the logger onFINER
.LOG.isLoggable
must be executed twice, 1st before the method-call of.finer(
and inside the methodfiner
a second time.- A StringBuilder is created on the mathematical operatior
+
. - I must import the class
Level
. - A different Thread could set the Driver to
null
and prevent the log from logging this line.
What if I use Lambdas instead?
Example:
LOG.finer(()->"The driver of the car is '", ()->car.getDriver().getName(), ()->"'.");
Wherat finer
is defined as
public void finer(ObjectReturningFunctionalInterface ... arguments) {
We can solve all the cons we see in the classic style if we catch all argument evaluation exceptions.
Why is it a bad idea?