The scenario is that I need to access a value at least twice. I.e. I am using logger to keep track of what is happening in the application. I want to log the name of the object, that function is working on, and later on do something with the very same name(i.e check if it contains some string or put it into an array).
Storing the name in variable:
foo(Bar bar){
String name = bar.getName();
logger.info("I am working with "+name);
this.doSomethingWith(name);
}
Or calling getName() twice:
foo(Bar bar){
logger.info("I am working with "+bar.getName());
this.doSomethingWith(bar.getName());
}
I understand, that in the first scenario, I will create a new String, assign a value to it and then retrieve this value twice. This way I am using more memory resources, correct?
In second scenario, am I accessing object bar twice and then accessing it’s name twice. I suppose this is not a DRY approach. But on the other hand I am not repeating myself in the memory, correct?
Which approach is better?
Personally, I prefer the second approach.
Indeed, I usually create temporary variable solely when necessary.
Martin Fowler ( http://en.wikipedia.org/wiki/Martin_Fowler ) also follows this guideline. He relates it within his book that I’ve read:
http://www.amazon.fr/Refactoring-Improving-Design-Existing-Code/dp/0201485672
A free extract of its book concerning this topic is here:
http://sourcemaking.com/refactoring/replace-temp-with-query
Some people would argue removing temporary variables could lead to performance issue.
As Martin Fowler says:
But anyway, it’s a matter of taste. Some people find more readable the first approach, others the second. I really prefer the second because I hate temporary variables adding lines for no real values 🙂