Re: Multiple return statements in a function.

From: Date: Thu, 23 Apr 2009 15:22:59 +0000
Subject: Re: Multiple return statements in a function.
References: 1 2 3 4 5  Groups: php.general 
Request: Send a blank email to php-general+get-291877@lists.php.net to get a copy of this message
At 10:25 AM -0400 4/23/09, Robert Cummings wrote:
On Thu, 2009-04-23 at 10:14 -0400, tedd wrote: However, I am saying (after years of reading other people's code) it
is generally much easier to read code that follows "Structured Programming" than it is to read code that doesn't.
Actually I use an early return as much as possible also. If there are 5 conditions which disqualify the rest of the function from running then they'll all be listed one after the other at the top of the function. This way it's very easy to see exactly what doesn't qualify for evaluation. Additionally, it saves on the need for that many levels of indentation or making an overly complex conditional. I find it much more intuitive than mentally tracking several levels of indentation and scrolling to the bottom of the function. Cheers, Rob.
Rob: Again, I'm not arguing the point -- we actually agree. I have functions where I do that as well. My only criteria is how easy my functions are to read and understand. If by placing function entry-criteria at the beginning of the function and then returning nulls (or whatever) makes it easier for someone to review your code and understand what it does, then by all means do it. But I am sure that both of you have reviewed functions that have multiple returns spread throughout where you thought "What the hell is this? Just what is this function returning?" That is what I am addressing. The OP asked which was the better practice and I replied that it is USUALLY good practice to have only one return and have it at the end of your function -- I stand by that. Cheers, tedd -- ------- http://sperling.com http://ancientstones.com http://earthstones.com

« previous php.general (#291877) next »