1

I often write functions with conditional branches like this:

function f
  if(X) {
    do something minor;
  }
  else if(Y) {
    do something minor;
  }
  else {
    do a whole lot of stuff;
  }

I could achieve the same results doing:

function f
  if(X) {
    do something minor;
    return;
  } 

  if(Y) {
    do something minor;
    return;
  }

  do a whole lot of stuff

I like that the second one doesn't require I indent the majority of my code, but am not sure if this is considered good practice or not. Since there's no common code following the conditional it seems justifiable to do a hard return. But the first style seems to have merits also.

Bhargav Rao
  • 41,091
  • 27
  • 112
  • 129
aw crud
  • 8,511
  • 17
  • 67
  • 112
  • You might also question if it makes sense to have all three cases in a single function. Sometimes it does, sometimes it doesn't. I prefer the second form when the first two cases can fit easily on an 80x25 terminal, and I prefer the first form when the first two cases cannot easily fit on an 80x25 terminal. – sarnold Mar 08 '11 at 12:52
  • you can also try http://codereview.stackexchange.com/ – Nick Dandoulakis Mar 08 '11 at 12:56
  • 1
    related: [Should a function have only one return statement?](http://stackoverflow.com/questions/36707/should-a-function-have-only-one-return-statement) – Nick Dandoulakis Mar 08 '11 at 13:06

3 Answers3

1

Personally I think using lots of return statements can make code less readable

I often layout my code so that the 'main' body of a function doesn't all have to be indented, in your case:

function f
  if (X || Y) {
    if (X) do something minor;
    if (Y) do something minor;
    return; // with comment explaining what we're doing
  } 

  do a whole lot of stuff
cusimar9
  • 4,781
  • 4
  • 21
  • 30
1

First; by now, you should use an editor that takes care of indention for you.

Second; Having several return statements can be confusing. One function one exit point.

Third; If "a whole lot of stuff" could be written as separate functions, do it.

But then again, it's all a matter of taste.

klang
  • 514
  • 3
  • 12
0

Try using switch/case:

function f
{
  switch(Z)
  {
       case X:
          do something...
          break;
       case Y:
          do something...
          break;
       default:
          f2();
  }

}

function f2{do other stuff...

}

Bjorkson
  • 491
  • 1
  • 5
  • 12