returning boolean variable or returning condition both are same?

Akash Chavan :

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.

GhostCat salutes Monica C. :

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 ...

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=91903&siteId=1