0

In Java, it's allowed to have assignment in a if condition, meaning we can have code like this:

List<T> result;
if ((result = getResultFromA())) == null) {
  result = getResultFromB();
}
return result;

Which I think is equivalent to:

List<T> result = getResultFromA()
if (result == null) {
  result = getResultFromB();
}
return;

I know the second one is more readable, but I'm wondering if there is any difference in terms of efficiency or performance? Is the first style a bad practice? I would appreciate any ideas.

Update: Thanks for all these great ideas. Actually the question should be: which of these two syntaxex should be followed? Apart from readability, is there any other reason why we prefer the second style?

Tonysuss
  • 1
  • 1
  • 4
    If you think the second is more readable, then use the second one. That's the only reason to prefer one of those two options over the other. – khelwood Aug 06 '20 at 20:54
  • 3
    Don't worry about performance at this level. Focus on writing code that is easy to read. The only people who are worrying about potential micro-optimizations like this are writing incredibly specific performance-sensitive applications (think HFT), and that's only after they optimized literally everything else first. They are also probably a lot smarter than you and me. And most people writing code like that aren't using Java anyway. If you really care about measuring any performance difference, see the linked duplicate. – Michael Aug 06 '20 at 21:06
  • Being more readable goes a long way. It will help the next people maintaining your code. That itself already increases productivity beyond yourself. – froi Aug 06 '20 at 22:36
  • Well, how do you think about it? Do you think "get the result; if it's null then try another way" or do you think "if get the result is null then try another way"? I suggest the former is what you're thinking, and so that is what you should write. The real question is, why declare 'result' on one line and assign it on the next? – user13784117 Aug 06 '20 at 23:14
  • 1
    I disagree this is a duplicate of a micro-benchmarking question. The question is, what should the OP write, and the answer is clearly not a performance issue. – user13784117 Aug 06 '20 at 23:17
  • I agree with 4117. This question should not have been closed. The answer to the question is absolutely not at the link posted. The question is about choosing between two syntaxes. – Jonathan Locke Aug 07 '20 at 05:17
  • This is just a matter of opinion, and thus an off-topic question. The closure as a duplicate might be wrong, but closing itself was warranted. – Mark Rotteveel Aug 08 '20 at 08:58
  • Closing for an incorrect reason is as bad as posting an incorrect answer. In fact, it **is** posting an incorrect answer, since if the OP follows the "helpful" link, he's none the wiser. – user13784117 Aug 10 '20 at 00:50

0 Answers0