I’m curious about a small Java code-style / maintainability question. Suppose I have something like:
void myFunction(Payload payload) {
log.info("Calling function using {}", payload.getCode());
// some other instructions..
myFoo(payload.getCode());
// some other instructions..
myBar(myVariable, payload.getCode());
// some other instructions..
}
I usually prefer extracting the repeated getter call into a local final variable:
void myFunction(Payload payload) {
final String code = payload.getCode();
log.info("Calling function using {}", code);
// some other instructions..
myFoo(code);
// some other instructions..
myBar(myVariable, code);
}
My reasoning is mostly:
- readability / avoiding repetition;
- maintainability, especially if the way
codeis obtained changes later; - making it explicit that all these calls use the same value;
However, I don’t seem to see this pattern used very often unless the expression itself is relatively complex. Is there a reason Java devs generally prefer calling a simple getter repeatedly instead of introducing a local var?
Would you consider the second version cleaner, unnecessary abstraction, or mostly a matter of style? And are there any cases where one approach is objectively preferable? I'm also interested in performance impacts here.
Thanks