Re: Multiple return statements in a function.
| From: | tedd | Date: | Thu, 23 Apr 2009 14:14:28 +0000 |
| Subject: | Re: Multiple return statements in a function. | ||
| References: | 1 2 3 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-291870@lists.php.net to get a copy of this message | ||
At 2:19 PM +0100 4/23/09, Tony Marston wrote:
"tedd" <tedd.sperling@gmail.com> wrote in message It's called "Structured programming" -- one way in and one way out of aTony: Don't get your panties in a knot. :-) I have 44 years of programming under my belt, so what? However, I wish I could remember everything I learned during that time. But what I do remember is there's a school of thought called "Structured Programming" that has a doctrine in which every function should have only one entry and exit point. Now maybe you want to argue with that concept, that's fine -- but the point remains this is a "rule" under "Structured Programming". That's history. Now, I usually follow that rule for I have learned from experience that in most cases, it is easier to read what is going on in a function if you only have one exit. As I said in my post, there are of course exceptions. There are times that requiring a function to have a single exit point will unnecessarily create code that's hard to read -- so doing it differently is something to consider in those cases. If you want to have an immediate exit point in your functions and that makes your code more readable, then that's fine and I'm not arguing that point. 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. Cheers, tedd -- ------- http://sperling.com http://ancientstones.com http://earthstones.comfunction. There are, of course, exceptions where it might help others reviewing your code to see what's going on, such as returning a null value if the argument(s) provided are not suitable. But normally the rule is, do not provide an exit from a function in more than one place.There is no such "rule", it is a matter of personal preference. As a previous poster has already said, if you want to leave a function early and ignore all subsequent processing it is easier to understand if you return immediately rather than have a mechanism to jump over the remaining code to a single return point. In the good old days we used to use the GOTO in COBOL to jump to the exit point, but then people found a way to abuse GOTO in very imaginatve ways.The "benefit" is easier to read code.I think that an immediate return is easier to read, but what do I know - I've only been programming for 30 years. -- Tony Marston