...
Code Block |
---|
|
validateUser(User usr)
{
if(validUsers.contains(listContains(validUsers, usr))
{
return 1;
}
return 0;
}
processRequest(User usr, Request request)
{
if(!validateUser(usr))
{
return "invalid user";
}
else
{
serveResults();
}
}
|
...
Code Block |
---|
|
validateUser(User usr)
{
if(allUsers.list_contains(allUsers, usr) == 0)
{
return 303; // user not found error code
}
if(validUsers.list_contains(validUsers, usr) == 0)
{
return 304; // invalid user error code
}
return 0;
}
processRequest(User usr, Request request)
{
if(!validateUser(usr))
{
return "invalid user";
}
serveResults();
}
|
...
Code Block |
---|
|
validateUser(User usr)
{
if(validUsers.list_contains(validUsers, usr))
{
return 1;
}
return 0;
}
processRequest(User usr, Request request)
{
if(validateUser(usr) == 0)
{
return "invalid user";
}
else
{
serveResults();
}
}
|
...
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 |
---|
|
if(foo() == 1) // Will evaluate to False if foo() returns 2, though that may logically imply a result of True.
{
return 1;
}
LinkedList bannedUsers;
is_banned(User usr) {
int x = 0;
Node cur_node = (bannedUsers->head);
while(cur_node != NULL) {
if(strcmp((char *)cur_node->data, usr->name) {
x++;
}
cur_node = cur_node->next;
}
return x;
}
processRequest(User usr)
{
if(is_banned(usr) == 1)
{
return;
}
serveResults();
}
|
If a banned user is listed twice, he gets access. Although check_user follows the common convention of returning non-zero for true, processRequest only checks for equality with 1.
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 |
---|
|
if(foo() \!= 0) // Given convention (2), this will always yield the intended behavior.
{
return true
LinkedList bannedUsers;
is_banned(User usr) {
int x = 0;
Node cur_node = (bannedUsers->head);
while(cur_node != NULL) {
if(strcmp((char *)cur_node->data, usr->name) {
x++;
}
cur_node = cur_node->next;
}
return x;
}
processRequest(User usr)
{
if(is_banned(usr) != 0)
{
return;
}
serveResults();
}
|
Noncompliant Code Example
...