Java – if i have many calls of single method that returns field value, is it better to make a local variable

designjavaprogramming practices

In a method, i have calls of single method of another object that returns field value, like foo.value(), which is defined like Field value() {return this.value;} Is it better to make a local variable, like Field value = foo.value() and use it. Or use many method calls of a single method? Why? How does it correlate with number of method calls, like for 3, 5, 10 what will be better and why it may be a concern?

Edit: field doesn't change anyhow during the flow of a method, just the same value all the time.

Edit2: does it depend on programming language? If it's important, it's java.

Best Answer

For the sake of clarity, I would suggest using final Field value = foo.value() (final since you specify the value doesn't change) if you have more than a single method call. Performance wise there will be no difference, the JIT compiler will likely completely inline all the calls to a simple accessor method.

There are a few reasons to prefer this: most important is that this shows whoever is reading the code that you are definitely using the same variable, and it definitely does not change (by use of final). This is more clear than using multiple methods calls - whoever is reading it will need to chase down if it really is using the same thing each time you call a method. Less importantly, if the method name changes, it only needs to change in one spot here, instead of needing to modify it at each point where it is used.

Related Topic