3

I have been give comment to not use variable in the return statement and instead use condition directly in return statement. Is there any difference between line 3 and 4 in the code below?

String str = "Hello Sir";
boolean flag = str.contains("Hello");
return(flag);
// instead ask to use below
return(str.contains("Hello"));

I prefer to use variable, as in complex calculations those are helpful in debugging.

Linus Fernandes
  • 498
  • 5
  • 30
Akash Chavan
  • 325
  • 2
  • 7
  • 22

2 Answers2

7

There is really no difference here. That variable lives on the stack, so does the value that is returned directly.

So, theoretically, there might be minor minor performance differences between them.

But rest assured: readability is much more important here, therefore I am with you: you can use such an additional variable when it helps the reader. But when you follow clean code principles, another option would be to have a method that only computes that condition and returns the result.

Please note: the "common" practice is to avoid additional variables, so many tools such as PMD or even IDEs suggest you to directly return (see here for a discussion of this aspect).

And finally, coming back on performance. If your method is invoked often enough, the JIT will inline/compile it anyway, and optimize it. If the method isn't invoked often enough, what would we care about a nanosecond more or less of execution time ...

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • Also I would say that the JVM is probably clever enough to simply optimize away the `boolean flag` line anyways. Probably the bytecode will be exactly the same. – Ben Jul 09 '18 at 12:33
  • @Ben The default javac isn't doing much of optimisations. Constant folding is about it. So the bytecode might be different. What the JIT does is of course completely different. – GhostCat Jul 09 '18 at 12:35
  • You are welcome, and it helped adding another bit of information to my answer! – GhostCat Jul 09 '18 at 12:37
-2

i don't see a difference.. basically it is returning the value directly vs returning a variable containing the value..

Edit: OK the answer looked like a rewrite of the question.. what i meant is that its passing a value (true/false) or passing a variable for the system to unwrap it's value (var -> true/false)

so, better performance for the first option.. but nothing worth going against your personal preference for..

Me1o
  • 1,629
  • 1
  • 6
  • 8
  • 1
    This would be a mediocre answer, it is nowhere a reasonable answer! Please improve it, or delete it. – GhostCat Jul 09 '18 at 12:37