Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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.

share|improve this question
    
This question depends on the programming language. –  Uwe Plonus Jun 13 '13 at 8:46
add comment

2 Answers

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.

share|improve this answer
add comment

If you are sure that the value does not change there is no reason to save this in a local variable.

Java HotSpot has the ability to detect such repeated call and will inline the method call.

Therefore it is more a matter of taste than anything else.

EDIT Also for renaming: most IDEs support refactoring method calls.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.