Are multiple return statements a bad practice?

  • (2 Pages)
  • +
  • 1
  • 2

15 Replies - 1171 Views - Last Post: 02 July 2013 - 08:33 PM Rate Topic: -----

#1 slehmann101  Icon User is offline

  • D.I.C Head

Reputation: 21
  • View blog
  • Posts: 146
  • Joined: 30-November 11

Are multiple return statements a bad practice?

Posted 02 July 2013 - 12:30 PM

I was recently entered into a competition(the iverson exam), in which one of my solutions had a method along the lines of:

method(){
if(x){
return 5;

}
return 2;

}

however the answer was along the lines of :

int returnable;
if(x){
returnable = 5;

}else{
returnable= 2;
}
return returnable;
}


My question is why go to all this effort to have one return statement. Is it a poor practice? if so can you explain why?

Is This A Good Question/Topic? 0
  • +

Replies To: Are multiple return statements a bad practice?

#2 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 10803
  • View blog
  • Posts: 40,262
  • Joined: 27-December 08

Re: Are multiple return statements a bad practice?

Posted 02 July 2013 - 12:34 PM

It's a stylistic decision. I personally find the first example to be cleaner. It's really up to you as the developer. Just try and keep in mind readability and clarity in your choice.
Was This Post Helpful? 3
  • +
  • -

#3 modi123_1  Icon User is online

  • Suitor #2
  • member icon



Reputation: 9570
  • View blog
  • Posts: 36,240
  • Joined: 12-June 08

Re: Are multiple return statements a bad practice?

Posted 02 July 2013 - 12:35 PM

What if I wanted to execute more of the method and not immediately leave? Sure in that small example you can go either way, but when I am writing more fleshed out code I typically stick with the variable and setting the return value as it goes through the method (because I want to do other things than exit)... and instead of having my code in two different ways I keep it one way.. the one with the most utility.
Was This Post Helpful? 1
  • +
  • -

#4 CasiOo  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1423
  • View blog
  • Posts: 3,165
  • Joined: 05-April 11

Re: Are multiple return statements a bad practice?

Posted 02 July 2013 - 01:02 PM

The style I like the most when the method is simple like that is
public int someMethod() {
    return x ? 5 : 2;
}


So I would go with neither of your two examples :P

No but really.. There is nothing wrong with multiple return statements
It depends on the method really. Also if you are allowed to return early. Something important might happen later on in the method

A good example would be when looking for an element in an array
It is much cleaner to return early
public Object find(Object criteria) {
    for (Object element : array)
        if (element.getFoo().equals(criteria))
            return element;

    return null;
}


Was This Post Helpful? 1
  • +
  • -

#5 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4421
  • View blog
  • Posts: 12,286
  • Joined: 18-April 07

Re: Are multiple return statements a bad practice?

Posted 02 July 2013 - 01:14 PM

I have seen the recommendation of one return statement before in several sources I have seen, but in practice I have seen multiple return statements. I see no issue with multiple returns as long as you are not abusing it with returns all over the place. Nothing wrong with them and macosxnerd101 is right, it is a style choice.

:)
Was This Post Helpful? 0
  • +
  • -

#6 Flukeshot  Icon User is offline

  • A little too OCD
  • member icon

Reputation: 417
  • View blog
  • Posts: 1,030
  • Joined: 14-November 12

Re: Are multiple return statements a bad practice?

Posted 02 July 2013 - 03:50 PM

An example of a toString() method I wrote recently, for a Card class. Perhaps it can be improved, but it uses both of your examples techniques in conjunction with one another.

public String toString() {
	String title = "";
	switch(faceValue) {
	case -1:
		return "Joker"; //early return technique
	case 1:
		title = "Ace";
		break;
	case 11:
		title = "Jack";
		break;
	case 12:
		title = "Queen";
		break;
	case 13:
		title = "King";
		break;
	default:
		title += faceValue;
	}
	return title + " of " + suit; //variable return technique


Was This Post Helpful? 0
  • +
  • -

#7 cfoley  Icon User is offline

  • Cabbage
  • member icon

Reputation: 2069
  • View blog
  • Posts: 4,307
  • Joined: 11-December 07

Re: Are multiple return statements a bad practice?

Posted 02 July 2013 - 04:46 PM

Any of the three techniques is fine. The best one will depend on the situation. A sensible guideline, although not a hard and fast one, would be to stick with the same one within a source file.

Quote

Perhaps it can be improved


I love a challenge :)/>

public String toString() {
	if (faceValue == -1) {
		return "Joker";
	} else {
		return title() + " of " + suit;
	}
}

private String title() {
	switch(faceValue) {
	case 1:
		return "Ace";
	case 11:
		return "Jack";
	case 12:
		return "Queen";
	case 13:
		return "King";
	default:
		return "" + faceValue;
	}
}


This post has been edited by cfoley: 02 July 2013 - 04:47 PM

Was This Post Helpful? 1
  • +
  • -

#8 Flukeshot  Icon User is offline

  • A little too OCD
  • member icon

Reputation: 417
  • View blog
  • Posts: 1,030
  • Joined: 14-November 12

Re: Are multiple return statements a bad practice?

Posted 02 July 2013 - 04:55 PM

public String toString() {
	if (faceValue < 0)
		return "Joker";
	return title() + " of " + suit;
}

private String title() {
	switch(faceValue) {
	case 1:
		return "Ace";
	case 11:
		return "Jack";
	case 12:
		return "Queen";
	case 13:
		return "King";
	default:
		return "" + faceValue;
	}
}



How many characters can we knock off this? Without getting carried away of course. :P
Was This Post Helpful? 0
  • +
  • -

#9 cfoley  Icon User is offline

  • Cabbage
  • member icon

Reputation: 2069
  • View blog
  • Posts: 4,307
  • Joined: 11-December 07

Re: Are multiple return statements a bad practice?

Posted 02 July 2013 - 05:16 PM

You can get really carried away with that sort of thing. I was aiming for clarity. I agree that removing the braces form the if looks cleaner but a lot of people object to it. I wonder what the value of suit is for a joker. Null?

public String toString() {
	return titleOrNumber() + ofWhatSuit();
}

private String titleOrNumber() {
	switch(faceValue) {
	case -1:
		return "Joker";
	case 1:
		return "Ace";
	case 11:
		return "Jack";
	case 12:
		return "Queen";
	case 13:
		return "King";
	default:
		return "" + faceValue;
	}
}

private String ofWhatSuit() {
	return (suit == null) ? "" : (" of " + suit);
}

Was This Post Helpful? 0
  • +
  • -

#10 Flukeshot  Icon User is offline

  • A little too OCD
  • member icon

Reputation: 417
  • View blog
  • Posts: 1,030
  • Joined: 14-November 12

Re: Are multiple return statements a bad practice?

Posted 02 July 2013 - 05:29 PM

If we're aiming for clarity, I object to bouncing around multiple methods to return such simple logic. But for the sake of the topic, I think this proves that multiple return statements are not bad practice.
Was This Post Helpful? 0
  • +
  • -

#11 cfoley  Icon User is offline

  • Cabbage
  • member icon

Reputation: 2069
  • View blog
  • Posts: 4,307
  • Joined: 11-December 07

Re: Are multiple return statements a bad practice?

Posted 02 July 2013 - 05:54 PM

If we're aiming for clarity, I object to bouncing around multiple methods to return such simple logic.


Well, we could argue about what makes clear code. Each of those three methods does one job. The higher level one reads like a story and the lower level ones are so simple, you can understand them at a glance. Well, almost. On reflection, I would use an if statement in ofWhatSuit(). In a source file, they should be next to each other in the order above so when someone reads down the source file, they can see the definitions of the helper methods right after their context.

It's also possible that titleOrNumber() could be useful in other places.
Was This Post Helpful? 0
  • +
  • -

#12 jon.kiparsky  Icon User is offline

  • Pancakes!
  • member icon


Reputation: 7999
  • View blog
  • Posts: 13,701
  • Joined: 19-March 11

Re: Are multiple return statements a bad practice?

Posted 02 July 2013 - 05:59 PM

CasiOo has got it right, for my money: if this is an issue, then your method is too long. Refactor, break it down.

This may be the best thing I've got from my exposure to "functional" programming techniques: small functions, well-named, are the way to go. But really, this is just basic Unix design philosophy: a single unit of functionality should do one thing well.
Was This Post Helpful? 1
  • +
  • -

#13 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8346
  • View blog
  • Posts: 31,904
  • Joined: 06-March 08

Re: Are multiple return statements a bad practice?

Posted 02 July 2013 - 07:56 PM

It is personal taste but some time employer might force the use of of technic rather than the other one
In the 80's I have seen a place where the law was "only one return by subroutine" so a Fortran program had if statements imbricated up to 35 level to avoid a simple return in the middle of the routine

if(!condition1) {
   do stuff
   if(!condition2) {
      do stuff
      if(!condition3) {
         do stuff
         .....
                               if(!condition35) {
                                  do stuff
                               }
               ....
       }
    }
}
return;   <---- congratulation single return


rather than
  if(condition1)
     return;
  do stuff
  if(condition2)
     return
  do stuff
  if(condition3)
     return; 


personnaly I prefer the second one

The best example is the validPassword method.... return when something breals the condition

bolean validPassword(String pwd) {
   int len = pwd.length();
   if(len < 6)              // check at least 6 character
      return false;

   int nbLetter = 0;
   int nbDigit = 0;
   for(int i = 0; i < len; ++i) {
      char digit = pwd.charAt(i);
      if(!Character.isLetterOrDigit(digit))   // check all letter or digit
         return false;
      if(Character.isLetter(digit))           // count each type
         ++nbLetter;
      else
         ++nbDigit;
   }
   if(nbLetter == 0)       // not a least a letter
      return false;
   if(nbDigit == 0)        // not at least a digit
      return false;

   ... other tests

   return true;     <--- passed all tests
}


Was This Post Helpful? 3
  • +
  • -

#14 l3g3ndary  Icon User is offline

  • New D.I.C Head

Reputation: 4
  • View blog
  • Posts: 14
  • Joined: 01-July 13

Re: Are multiple return statements a bad practice?

Posted 02 July 2013 - 08:07 PM

I'm not an expert but I like the first one better it's cleaner and easier to read.
Was This Post Helpful? 0
  • +
  • -

#15 jon.kiparsky  Icon User is offline

  • Pancakes!
  • member icon


Reputation: 7999
  • View blog
  • Posts: 13,701
  • Joined: 19-March 11

Re: Are multiple return statements a bad practice?

Posted 02 July 2013 - 08:10 PM

Quote

awful example snipped...


Gah, what a horror! But yeah, they got their single return. Whoop!



In your password example, I see a prime opportunity to produce clarity by converting it to a set of high-level functions, so all of the statements in the method are at the same level of abstraction.

View Postpbl, on 02 July 2013 - 09:56 PM, said:

The best example is the validPassword method.... return when something breals the condition

bolean validPassword(String pwd) {
   int len = pwd.length();
   if(len < 6)              // check at least 6 character
      return false;

   int nbLetter = 0;
   int nbDigit = 0;
   for(int i = 0; i < len; ++i) {
      char digit = pwd.charAt(i);
      if(!Character.isLetterOrDigit(digit))   // check all letter or digit
         return false;
      if(Character.isLetter(digit))           // count each type
         ++nbLetter;
      else
         ++nbDigit;
   }
   if(nbLetter == 0)       // not a least a letter
      return false;
   if(nbDigit == 0)        // not at least a digit
      return false;

   ... other tests

   return true;     <--- passed all tests
}



This is not bad, but I'd want something more like this:

bolean validPassword(String pwd) {
   return validLength(pwd) &&
          validCharacterDistribution(pwd) &&
          passesReuseCheck(pwd) &&     // have they used this one recently?
          ...
          isNotJustTheWordPassword(pwd);  // or whatever tests you want
}      



though the names might be made better, of course. The validCharacterDistribution() would of course call some helper methods.

This post has been edited by jon.kiparsky: 02 July 2013 - 08:44 PM

Was This Post Helpful? 1
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2