Loggers are not constants
Loggers are not constants, they are mutable objects.
I am currently working on a legacy Java/Spring codebase littered with calls to LOG and LOGGER, proudly declared as static final. There appear to be sound justifications for adopting this convention (besides avoiding Checkstyle complaints) but sometimes it is useful to reflect on how we ended up here.
Loggers have traditionally been declared static as their construction was considered expensive and therefore justified a singleton status. Times have changed along with coding conventions.
Most of the applications in this particular codebase are of the vanilla Spring application variety, namely singleton services processing value objects on multiple threads.
Loggers used by service singletons are obviously singletons themselves and clearly don't warrant this premature optimization. Loggers in value objects shouldn't be there.
A grey area exists for short lived domain objects, say some business logic encapsulated in a function that would log input arguments and the result. The solution is to have the object factory inject the logger at object construction time. Dependency injection ensures that logging is just another service, singleton or not.
A further argument against using static final loggers is the increased use of semantic logging. The implications are that if, in order to unit test the logging feature, the object under test requires the static mocking capabilities of PowerMock then you're doing dependency injection incorrectly or not at all.
In another example, this practice was followed to the absurd extreme with SimpleDateFormat. Not only is this not a constant but the methods are not thread-safe. Declaring it as such merely increases the likelihood of multiple threads executing the unsafe methods concurrently, even more so when running in a multi-application container.
The Google Java Style guide suggests some reasonable conventions for constant names.
Forgetting why we started doing it in the first place and blindly following the static final Logger convention is, at best, premature optimization and, at worst, a shining example of donning the coconut headphones.
posted by James Gemmell on Tue, 24 Nov 2015 at 22:37 | permalink