I have coded like follows,
for(int i=0 ; i<n; i++){
String a = someObject.getFirstName(); //may not come same value..
doManipulationon(a);
}
During code review, people asked me to remove the string literal a and use someObject.getFirstName() directly for manipulation. They afraid that string object will be created in heap on every iteration.
Is this the correct way?
I thought assigning the getter into a string variable gives code more readable.
First there is no string literal here.
A string literal is a string expression enclosed in double quotes, like “dog”.
Your reviewers are stating that they do not like the temporary variable
aused to hold an expression that you are manipulating in the very next line.Apparently they want you to say
Removing temporary variables leads to more compact code. This is usually, but not always, a good idea. You can use temporary variables when your “intermediate expression” has an interesting meaning, but in your case, using the name
awas not helpful. You could have saidIn long expressions, especially, assigning partial results to variables that are given meaningful names does add to readability.
Oh, and as to their comment about new string objects being added to the heap in your example — no, none will.