2009/6/10 Clancy <[email protected]>
> On Tue, 09 Jun 2009 12:22:22 -0400, [email protected] (Robert Cummings)
> wrote:
>
> >Craige Leeder wrote:
> >> I'm not sure I agree with NEVER using else. Sometimes else is a very
> >> logical way to organize code. However, it should not be used for data
> >> validation IE:
> >>
> >>
> >> function myValidatorFunc($data) {
> >> if (empty(data)) {
> >> return false;
> >> } else {
> >> if (!is_numeric($data)) {
> >> return false;
> >> } else {
> >>
> >> }
> >> }
> >> }
> >>
>
Sure - these control structure doesn't make sense - but who would write it
*like that*?
Guess 99% would rather write smth like that:
if (empty($data) || !is_numeric($data)) {
return false;
}
Whis is good.
:-)
>
> >>
> >> It's all about how deep you nest your code, and keeping the flow clean.
> >> That code would be much more readable as such:
> >>
> >> function myValidatorFunc($data) {
> >> if (empty(data)) {
> >> throw new BadMethodCallException("Paramater data missing");
> >> }
> >> if (!is_numeric($data)) {
> >> throw new InvalidArgumentException("Paramater data should be an
> >> integer.");
> >> }
> >> }
> >>
> >> See the difference?
> >
> >I believe the article was suggesting not ending a function that returns
> >a value with no return. So rather than return in the else, return
> >outside the else as the last expression of the function. This way it is
> >clear that the function returns a value.
> >
> >Contrast:
> >
> ><?php
> >
> >function foo( $foo )
> >{
> > if( $foo )
> > {
> > return true;
> > }
> > else
> > {
> > return false;
> > }
> >}
> >
> >?>
> >
> >Versus:
> >
> ><?php
> >
> >function foo( $foo )
> >{
> > if( $foo )
> > {
> > return true;
> > }
> >
> > return false;
> >}
> >
> >?>
> >
> >Personally, I also prefer the latter style.
>
> I don't particularly like scattered returns, and prefer
>
> Function foo;
> {
> result = false;
> if ( ) { $result = 'yellow'; }
> elseif ( ) { $result = 'blue'; }
> return $result;
> }
>
>
Well, I like the fact that the process is out of code, when you return
early. On the other hand, a single return is handy... Guess it depends on
the subject.
The discussion ... well.. sounds a bit like
"Use a red shoe, your blue ones are crap"
Regards