-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

1 Answers1

2

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
  • 898