What do you usually test for first: true or false?
Page 1 of 2 12 LastLast
Results 1 to 15 of 23

Thread: What do you usually test for first: true or false?

  1. #1
    Senior Member
    Join Date
    Mar 2009
    Posts
    812

    What do you usually test for first: true or false?

    Just something I've been wondering about lately and I have been trying to think of a consistent way of approaching it, but wanted to hear what others did in similar situations and if there was any reason behind it.

    Quite frequently when coding you have come across a situation where you have to test a boolean. Say you were looping through an array and displaying some tabular data. You would first check to make sure the array wasn't empty, and if it was, then display a message indicating there was no data to display, otherwise loop through the array and display the data. But how do you test it? Do you test for the positive or the negative (true or false)?

    Just a quick visualization for what I mean:
    PHP Code:
    //Testing for true (positive)
    if(empty($array))
    {
        
    //Echo out some message to the user
    }
    else
    {
        
    //Loop through array

    PHP Code:
    //Testing for false (negative)
    if(!empty($array))
    {
        
    //Loop through array
    }
    else
    {
        
    //Echo out some message to the user

    Is there any particular approach you take? Does it depend on the situation? Is it better to do one way over the other? It seems like a non-factor but I'm always curious on how others approach these kinds of things.
    Declare variables, not war.

  2. #2
    High Energy Magic Dept. NogDog's Avatar
    Join Date
    Aug 2006
    Location
    Ankh-Morpork
    Posts
    13,970
    While I'll freely break this rule whenever I feel (rightly or wrongly) that it makes the code clearer, the general rule I start from is to code the normal path first, then handle the exceptions afterward:
    PHP Code:
    function bar($param, &$error='')
    {
        
    $result false;
        if(
    is_numeric($param)) {
            if(
    $param 0) {
                
    // do something unbelievable with $params
                
    $result true;
            }
            else {
                
    $error 'param cannot be <= 0';
            }
        }
        else {
            
    $error 'param must be numeric';
        }
        return 
    $result;

    So it's not a case of true vs. false as much as normal vs. abnormal.
    Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be." ~ from Nation, by Terry Pratchett

    "But the main reason that any programmer learning any new language thinks the new language is SO much better than the old one is because hes a better programmer now!" ~ http://www.oreillynet.com/ruby/blog/...ck_to_p_1.html


    eBookworm.us

  3. #3
    Pna lbh ernq guvf
    Join Date
    Jul 2004
    Location
    Kansas City area
    Posts
    19,432
    I switch between first checking for the condition that I suspect is true the majority of the time and the condition where I'm checking if something equals zero. Both stem from optimizations for embedded code where I want to write the most optimized/efficient code (turns out there's a lot you can do other than throwing a "-O2" on the command line for your compiler and hoping for the best ).

  4. #4
    Settled 4 red convertible dalecosp's Avatar
    Join Date
    Jul 2002
    Location
    Accelerating Windows at 9.81 m/s....
    Posts
    7,719
    Quote Originally Posted by bradgrafelman View Post
    (turns out there's a lot you can do other than throwing a "-O2" on the command line for your compiler and hoping for the best ).
    Yup; learned that, somewhat, doing contests here all those years ago. Only problem being that in Web development management often does something like this:

    PHP Code:
    $wish "Last Week";
    define("SOON","Today");
    //etc.... 
    And, for the original question:

    I'm not certain. I generally think that I'm trying to avoid errors in my coding, therefore, if I'm coding a loop to play with an array, I will make sure that (!empty($array)) because I want to loop to succeed. Similarly (I think), I've noted that if I expect a value from a variable, I'll usually code the truth section first:

    PHP Code:
    if ($some_variable) {
       
    do_it();
    } else {
       
    //error code...

    I believe that comes from lots of code examples when we're learning at first, doesn't it?
    Last edited by dalecosp; 10-21-2013 at 06:42 PM.
    /!!\ mysql_ is deprecated --- don't use it! Tell your hosting company you will switch if they don't upgrade! /!!!\ ereg() is deprecated --- don't use it!

    dalecosp "God doesn't play dice." --- Einstein "Perl is hardly a paragon of beautiful syntax." --- Weedpacket

    Getting Help at All --- Collected Solutions to Common Problems --- Debugging 101 --- Unanswered Posts --- OMBE: Office Machines, Business Equipment

  5. #5
    Senior Member
    Join Date
    Mar 2009
    Posts
    812
    Thanks for the replies, guys. Looking through some old projects and websites I have done it looks like I'm kind of a mixed bag with the way I approach it, with a slight tendency to approach it like NogDog. Moving forward I think I'll add that to my "things I always do" while coding to keep it consistent. It's interesting looking back at old sections of code because I can tell how I was thinking at the time depending on what I was testing for first.
    Declare variables, not war.

  6. #6
    Settled 4 red convertible dalecosp's Avatar
    Join Date
    Jul 2002
    Location
    Accelerating Windows at 9.81 m/s....
    Posts
    7,719
    Quote Originally Posted by Bonesnap View Post
    Thanks for the replies, guys. Looking through some old projects and websites I have done it looks like I'm kind of a mixed bag with the way I approach it, with a slight tendency to approach it like NogDog. Moving forward I think I'll add that to my "things I always do" while coding to keep it consistent. It's interesting looking back at old sections of code because I can tell how I was thinking at the time depending on what I was testing for first.
    It is interesting looking back. Someone posted this recently: 7 reasons I switched back to PHP after 2 years on Rails. Interesting quote:

    Quote Originally Posted by Derek Sivers
    But the main reason that any programmer learning any new language thinks the new language is SO much better than the old one is because he’s a better programmer now!
    /!!\ mysql_ is deprecated --- don't use it! Tell your hosting company you will switch if they don't upgrade! /!!!\ ereg() is deprecated --- don't use it!

    dalecosp "God doesn't play dice." --- Einstein "Perl is hardly a paragon of beautiful syntax." --- Weedpacket

    Getting Help at All --- Collected Solutions to Common Problems --- Debugging 101 --- Unanswered Posts --- OMBE: Office Machines, Business Equipment

  7. #7
    Senior Member
    Join Date
    Jul 2007
    Posts
    3,664
    Quote Originally Posted by Bonesnap View Post
    because I can tell how I was thinking at the time depending on what I was testing for first.
    One thing I find from time to time, especially when looking at older code, is testing for whatever results in a shorter code block coming first
    PHP Code:
    if (true|false) {
        
    # 1-2 lines of code
    }
    elseif (
    the-other-condition) (
        
    # 1-2 pages of code…

    While I still rather see the beginning of both code blocks on screen at the same time than having to scroll and scroll and scroll to reach the second, today I'd would definitely refactor the code if I needed to make one single other change to it.

    Other than that, I try testing for end condition first, if applicable
    PHP Code:
    if ($done) {
        return;
    }
    # do more stuff code before returning 

  8. #8
    Senior Member
    Join Date
    Apr 2003
    Location
    Silver Lake
    Posts
    4,901
    I find myself checking if something is NOT there first and this more often than not results my code exiting the current function or throwing an exception. I think the primary goal is to avoid a situation where your code's logic results in deeper and deeper and deeper sets of brackets. It becomes impossible to read and maintain.

    PHP Code:
    // NO!!
    function mybadfunc() {
      if (
    $var) {
        
    // do something fancy here
      
    } else {
        
    // don't do anything here?
      
    }
    }

    // YES
    function mygoodfunc() {
      if (!
    $var) {
        throw new 
    Exception("var is empty.");
        
    // or return
      
    }

      
    // do something fancy
      // note that this code is not indented!


    IMPORTANT: STOP using the mysql extension. Use mysqli or pdo instead.
    World War One happened 100 years ago. Visit Old Grey Horror for the agony and irony.

  9. #9
    High Energy Magic Dept. NogDog's Avatar
    Join Date
    Aug 2006
    Location
    Ankh-Morpork
    Posts
    13,970
    Of course, there are those who insist a function/method should only have one return, who would then shudder at the thought of testing for an error and immediately returning if found. (I've been known to do it, but then nobody has ever accused me of being any type of coding purist.) Also, depending on what you are checking for, said purists would say if it's something like validating user input, it's not an exception, so you would not throw one for that situation. (I'm probably more closely aligned with that camp than I am the single-return camp.)
    Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be." ~ from Nation, by Terry Pratchett

    "But the main reason that any programmer learning any new language thinks the new language is SO much better than the old one is because hes a better programmer now!" ~ http://www.oreillynet.com/ruby/blog/...ck_to_p_1.html


    eBookworm.us

  10. #10
    Senior Member traq's Avatar
    Join Date
    Jun 2011
    Location
    so.Cal
    Posts
    949
    <-- not in the single-return camp.

    Conditional returns are better than nested statements, IMO. I'll usually do whatever tests will throw me out of the function quickest at the beginning. Usually that will actually result in an exception, but there are cases where valid input will result in no action, so I just return early. I do try to have only one "successful" return statement, and I try to keep it at the end. This is mostly for readability, I suppose.

    Testing for true/false first is similar: generally speaking, I test first for whichever condition will avoid the most code execution.

  11. #11
    High Energy Magic Dept. NogDog's Avatar
    Join Date
    Aug 2006
    Location
    Ankh-Morpork
    Posts
    13,970
    As they like to say in the Perl world: TMTOWTDI.
    Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be." ~ from Nation, by Terry Pratchett

    "But the main reason that any programmer learning any new language thinks the new language is SO much better than the old one is because hes a better programmer now!" ~ http://www.oreillynet.com/ruby/blog/...ck_to_p_1.html


    eBookworm.us

  12. #12
    Senior Member
    Join Date
    Jul 2007
    Posts
    3,664
    Quote Originally Posted by NogDog View Post
    Of course, there are those who insist a function/method should only have one return, who would then shudder at the thought of testing for an error and immediately returning if found.
    Would you care to elaborate / point to (re)sources? I have trouble coming up with any but three possible scenarios
    1. test for error, return without indication => agreed, sounds bad
    2. test for error, return with indication of this
    3. test for error, throw exception

    Quote Originally Posted by NogDog View Post
    Also, depending on what you are checking for, said purists would say if it's something like validating user input, it's not an exception
    And why not? Please elaborate, or point me to other (re)sources.

    As I understand exceptions and their usage, it goes a little something like this:
    1. when something is wrong, throw
    2. if you can handle -> do so!
    3. if not, log and rethrow (so the the exceptions are tiered just like the rest of the architecture and matches the same abstractions)

    Let's say your code ends up doing this
    PHP Code:
    $db = new PDO;
    $db->query("INSERT INTO table(varchar2) VALUES('abc')"); 
    The initial error would be a 22001 - data right truncated. Probably translated into "data too long for column 'varchar2'", which is turned into a PDO exception. Whatever the data layer receieves, it should definitely not expose pdo exceptions to the model. The best thing it could do would be to thow SomeDataLayerException which, in turn, would provide the model with enough information to, in turn, provide the view with
    Code:
    something* the view can use to somehow give the user appropriate feedback, such as indicating the offending input field
    * So what should "something" be?

    What makes more sense than throwing an exception? The error could be detected in two ways. The first is "while validating input, before trying to store" and the second is "oops, something went wrong further down the chain and they let me know - by throwing". If detected by catching an underlying exception, the proper course of action would be to log the error and rethrow (its own kind of exception, not a data layer exception), so that the model might handle it. If detected during validation, throw without logging. Having two ways of letting the view know "username is too long" makes no sense. The user doesn't care who detected the problem, and thus, the view has no reason to.

    Moreover, the reason you throw exceptions is so that if no point along the call chain knows how to handle the exception, the program should terminate with a big flashing "WTF!?". Not being able to create an account due to a too long username certainly seems like something a user should be informed about. If not nicely, then reasonably through an "Abnormal program termination. Unhandled exception 'Validation' with message: username too long".

    And just to be clear, I'm not claiming that you should "always throw exceptions". For example, let's say someone tries to create a new user, with a too long username, by sending a POST request to your REST api. Wether you detect that during validation or you detect it due to the 22001 data right truncated error being propagated through various exceptions up the chain, I'd still expect both to end in a 400 Bad Request.

    Where's the difference between that and an exception thrown by the model and caught by the view when they both reside within the same architecture?

  13. #13
    High Energy Magic Dept. NogDog's Avatar
    Join Date
    Aug 2006
    Location
    Ankh-Morpork
    Posts
    13,970
    I'm just going off of things I've read -- not necessarily from the finest sources -- over quite a few years. Like I say, I don't necessarily follow them, just use them as references when I catch myself breaking a "rule" to at least think twice about it before I go ahead and do it anyway.

    My local-scope understanding of exceptions has always been that they are supposed to be for handling situations that shouldn't happen, but just in case they do happen, you're ready for it. To my mind, a user neglecting to enter data in a required field is not a program exception, just a reasonably expected user error that I want to check for and deal with. I personally would rather return false from my input validation function and let the controller code (or whatever) that called that function decide what to do when it gets such a result. (And when the controller calls that function and gets a false result, that's a reasonably expected result, not something "exceptional".)

    That being said, there is a certain usefulness when working in a multi-tiered design of using the ability of exceptions to filter up through the stack until something catches it, so I can see a case for leveraging that ability in some situations that perhaps I would not define as "exceptional".

    As far as multiple returns, if you search on "single exit point", you'll find lots of stuff -- much of it indicating that few people care much about it these days.

    But like I tried to infer, I don't think there is one set of correct rules for all of this. I think the important thing is that we are thinking about it, so when we write code that throws an exception or returns early in a function, we at least pause for a few milliseconds to consider if that's really the way we want to do it, or if there's a better way to write it that will make more sense to us a year from now when we have to debug that code.
    Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be." ~ from Nation, by Terry Pratchett

    "But the main reason that any programmer learning any new language thinks the new language is SO much better than the old one is because hes a better programmer now!" ~ http://www.oreillynet.com/ruby/blog/...ck_to_p_1.html


    eBookworm.us

  14. #14
    Pedantic Curmudgeon Weedpacket's Avatar
    Join Date
    Aug 2002
    Location
    General Systems Vehicle "Thrilled To Be Here"
    Posts
    21,904
    Quote Originally Posted by johamafm
    Would you care to elaborate / point to (re)sources? I have trouble coming up with any but three possible scenarios
    1. test for error, return without indication => agreed, sounds bad
    2. test for error, return with indication of this
    3. test for error, throw exception
    Nicholas Wirth enforced this (thou shalt not have more than one point of return in thy function or procedure) in his design of Pascal.
    THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER
    FAQs! FAQs! FAQs! Most forums have them!
    Search - Debugging 101 - Collected Solutions - General Guidelines - Getting help at all

  15. #15
    High Energy Magic Dept. NogDog's Avatar
    Join Date
    Aug 2006
    Location
    Ankh-Morpork
    Posts
    13,970
    It can seem a bit forced if you try to stick with a single exit point. You tend to end up with something like:
    PHP Code:
    function myFunc($param, &$error)
    {
        
    $result false;
        if(
    is_int($param)) {
            if(
    $param != 0) {
                if(
    $param %== 0) {
                    
    $result doSomethingAmazingWith($param);
                }
                else {
                    
    $error "Must be even";
                }
            }
            else {
                
    $error "Cannot be zero";
            }
        }
        else {
            
    $error "Must be an integer";
        }
        return 
    $result;

    Then again, when you look at that, you can see the "normal" flow of what happens right away -- it's figuring out what happens when any of those checks fail that gets a bit messy. Then again, especially if it gets even more levels of nesting, maybe that's a sign that some of that validation stuff could be moved into a separate function? Then it might just be:
    PHP Code:
    function myFunc($param, &$error)
    {
        if((
    $result validator($param$error)) == true) {
            
    $result doSomethingAmazingWith($param);
        }
        return 
    $result;
    }

    function 
    validator($param, &$error)
    {
        
    $result true;
        if(!
    is_int($param)) {
            
    $result false;
            
    $error "must be integer";
        }
        elseif(
    $param == 0) {
            
    $result false;
            
    $error "Cannot be zero";
        }
        elseif(
    $param %!= 0) {
            
    $result false;
            
    $error "Must be even";
        }
        return 
    $result;

    Do I always code that way? Nope. But I do think about it and do follow that pattern when it seems to work smoothly. Other times it seems clumsy or overkill, and I have multiple returns, etc.
    Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be." ~ from Nation, by Terry Pratchett

    "But the main reason that any programmer learning any new language thinks the new language is SO much better than the old one is because hes a better programmer now!" ~ http://www.oreillynet.com/ruby/blog/...ck_to_p_1.html


    eBookworm.us

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •