Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#ffcccc
validateUser(User usr)
{
  if(allUsers.contains(usr) == false0)
  {
    return 303;  // user not found error code
  }
  if(validUsers.contains(usr) == false0)
  {
    return 304; // invalid user error code
  }

  return 0;
}

processRequest(User usr, Request request)
{
  if(!validateUser(usr))
  {
    return "invalid user";
  }

  serveResults();
}

...

The following is preferable for code maintenance. By defining what constitutes a failure and explicitly testing for it, the behavior is clearly implied and future modifications are more likely to preserve it.

Code Block
bgColor#CCCCFF

\#define FAIL 0

if(foo()==FAIL0) // explicit test for failure
{
  return 0;
}

...

The following is fairly common yet ignores the convention that most functions in C only guarantee a non-zero return value to indicate True/Yes/etc..

Code Block
bgColor#ffcccc

\#define TRUE 1

if(foo() == TRUE1) // Will evaluate to False if foo() returns 2, though that may logically imply a result of True.
{
  return true1;
}

Compliant Solution

Because most functions only guarantee a return value of non-zero for "true," the code above is better written by checking for inequality with 0 ("false") as follows.

Code Block
bgColor#CCCCFF

\#define FALSE 0

if(foo() \!= FALSE0) // Given convention (2), this will always yield the intended behavior.
{
  return true;
}

...