Reputation: 3381
Considering the following two methods:
public int add(int i, int j) {
return i + j;
}
public int add(int i, int j) {
int k = i + j;
return k;
}
They return the same value in this case for two given integer values as input but is there any difference in the two? I'm not sure but I'm thinking that there could be a slight performance advantage of using the first one while some may argue that the second one is more readable.
Personally I have always just returned the expression like the first method but going through a tutorial on the netbeans site they use the latter:
Is there any situation where one of the two has a significant advantage over the other if it's just a single calculation like the above?
Upvotes: 0
Views: 247
Reputation: 122026
Both the ways are good. But the thing is based up on the context.
Consider the below examples.
This is absolutely clean and more readable.
public int add(int i, int j) {
return i + j;
}
Now see in some situation's, what happens
public int calculate(int i, int j) {
int k= doAnotherCal(i,j);
int result= getThisDone(x);
return result;
}
So It just matter of context and readability. If you are worrying about memory/performance, modern JVM's are cleaver enough to resolve most of the memory related issues.
Aim for the readable code, So that everybody on the planet earth will be happy at the end :)
Upvotes: 0
Reputation: 724
The second way makes debugging easier ("return k" line is a perfect candidate for a breakpoint).
Upvotes: 3
Reputation: 79875
There is a huge advantage to using the second one, if you need to run your code with a debugger, for any reason. You can use the debugger to stop on return k;
and see the actual value that's about to be returned. You can't do that with the first form.
Many experienced programmers get into the habit of always using a variable for the return value, for this reason. They never know whether someone will need to use a debugger on the code later.
Upvotes: 0
Reputation: 8663
There won't be any performance difference, but second has little advantage, if expression is large, that first will look a bit creepy and confusing.
Upvotes: 0
Reputation: 27536
It really doesn't matter - compiler will remove that extra variable anyway during optimization. As almost always with these kind of questions, only thing that matters is code readability and maintainability so in this this case is really up to you (but I would prefer returning the expression, there is no reason for extra variable).
Upvotes: 3