Java - should I use constants for log messages?
compiler-construction, java, logging, string
Solution
I'm not sure what analyzer tool you use or how you configured it but the advice seems invalid to me. The Java compiler will already create string constants for you (it usually will not allocate a new String instance when the code calls the log method), so what would be the point to do this work manually?
If you put the string constant into an interface, you can share them between classes but not in the way you think you would: The Java compiler will copy the constant's value into the code where it's being used (so the resulting byte code will not have a reference to the interface anymore!)
My suggestion: Turn off this misleading warning.
Problem
Just a quick question about form. I am logging various error messages and am wondering if I should create a new string for the message within the log call, or create a constant string within an interface I am using to store other string constants, and then just reference that. I was using a code analyzer code and it alluded to the latter saying it was better practice to create a string constant and reference it, even if it the string is only used once. I am just wondering if this is indeed the case? Thanks in advance