-3

I'd like to ask about best practices on return statements.

So, what would be more preferable, something like...

...
String r = null;

if(var != null) {
  r = "NOT NULL!";
}

return r;

Or something like this...

...
if(var != null) {
  return "NOT NULL!";
}

return null;

In other words, one return statement and the value returned is controlled through the function flow, or several escape points?

Vers
  • 113
  • 5
  • 2
    Opinions on whether multiple returns is a good thing or a bad thing vary, and rather widely. For example, early return is highly frowned upon in Linux kernel programming but is strongly encouraged in C++. – David Hammen Jun 29 '17 at 11:15
  • @DavidHammen Thank you, will look into context for this. – Vers Jun 29 '17 at 13:48
  • @JörgWMittag You don't know the value of var, so no. – Vers Jun 29 '17 at 13:48

1 Answers1

1

You're looking at this the wrong way if you think it has to do with the number of return statements. Using a low or high amount of return statements by itself has no inherent value. Use the approach which best fits the application and programming flow while affording the best possible readability given all other concerns.

In most cases I find alterations of your second variant to be preferable (mainly for longer code segments) since it clearly denotes exit points.

Robzor
  • 888
  • 7
  • 11
  • 2
    I kind of have to disagree with you on this. I've recently been working with a function in a C++ program which has 71 return statements in it. It has been a nightmare to trace through and is full of memory leaks due to exits without proper cleanup. (Its another problem that the function is nearly 2500 lines.) I much prefer a single exit point and good use of exceptions, but it is all about what's best for the program. – bluegreen Jun 29 '17 at 19:07
  • @bluegreen I not so weirdly completely agree, which is why I said "Use the approach which best fits the application and programming flow while affording the best possible readability given all other concerns." I'm not saying that the latter is best in all situations but that I often find it the most useful solution. – Robzor Jun 29 '17 at 21:01