Re: Re: SHOULD I NOT USE "ELSE" IN IF STATEMENTS....?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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 {

      }
   }
}


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?

- Craige

O. Lavell wrote:
adam.timberlake wrote:

Im reading this post and i donnot understand how i should write my code:
http://www.talkphp.com/absolute-beginners/4237-curly-
brackets.html#post23720
Does it mean that i am to not write else statements in my ifs? or is it
just saying it is something i should avoid to rite better code?

please help me...

I happen to not agree completely with the post, because it seems to propose the use of things like "continue", "break" and "return" within control structures (the latter as opposed to at the end of a function, exclusively). Very bad practice in my opinion. Think of everything that has ever been said of "goto", it's just as bad for structured programming.

(however the use of "break" in "switch .. case" statements is an unfortunate necessity in PHP)

Not that I am diagramming much nowadays, but I still try to write code such that it could fit into a Nassi-Shneiderman diagram (NSD):

<http://en.wikipedia.org/wiki/Nassi-Shneiderman_diagram>

If you have never learnt to draw these then you probably should. It can be fun to do and they are very helpful for planning ahead and writing uncluttered code that can be easily debugged. And you will know you are nesting too deep when the diagram doesn't fit on the piece of paper you started on :)

To more directly answer your question I would say that if there is a *logical* requirement to use "else" after "if" then yes, you should use it and certainly not try to avoid it. There is absolutely nothing wrong with "else".




--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux