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
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.
Logging should be easy to add and remove; simply provide a very thin layer. And then there might be MessageFormats used, which are error prone/uncheckable when replaced by a constant name.
Also string constants are imported and then changes need no longer be detected, when the constant changes.
Also log strings are not very strict, informative on their own.
Better to mark those strings as non-internationalizable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With