In a typical spring mvc validator class, while inserting an errorCode value in the Errors object, what difference does it make between using a String (props.somefield.req
) like so
errors.rejectValue("elementId", "props.somefield.req");
verses a declared static final String ?
private static final String SOMFIELD_REQ = "props.somefield.req"; ...
errors.rejectValue("elementId", SOMFIELD_REQ);
Does it improve the performance even in a slightest way? I have read a few questions on stack overflow (String and final, Does it make sense to define a final String in Java?) but no one got around to answering this questions update question.
2
At runtime, it does not make a difference.
The point is readability – as a member variable, it likely is declared at the beginning of the class’ source code, and making it static means it doesn’t have to be allocated for each new instance of the class.
Making it final signifies to the reader that the value will not change (to the compiler too, but that’s less important here).
This way, there are no “magic values” buried in the implementation, and if a change is desired to the “constant”, it only needs to be changed in one place.
This basically mimics what a C programmer would do with a #define.
1
final
fields have many benefits!
Declaring fields as final
has valuable documentation benefits for developers who want to use or extend your class – not only does it help explain how the class works, but it enlists the compiler’s help in enforcing your design decisions. Unlike with final
methods, declaring a final field helps the optimizer make better optimization decisions, because if the compiler knows the field’s value will not change, it can safely cache the value in a register. final
fields also provide an extra level of safety by having the compiler enforce that a field is read-only.
Don’t try to use final
as a performance management tool. There are much better, less constraining ways to enhance your program’s performance. Use final
where it reflects the fundamental semantics of your program: to indicate that classes are intended to be immutable or that fields are intended to be read-only.
Before declare final fields, you should ask yourself: does this field really need to be mutable?