Better way to express "if false return false" construct

520 Views Asked by At

In many cases you have code like this (C-style pseudo code used):

bool checkCondition();

bool doSomething(){
   if (checkCondition() == false)
      return false;

   // do something
   return true;
}

I keep reusing this patter and every time wonder, if there is better way to express it?

Sometimes, the condition check can be left for the caller or asserted, but often condition check must be done inside the function.

You can get fancy and use exceptions, but result is almost the same code.

4

There are 4 best solutions below

4
Dorian Gray On

First I would express the negation like that:

 if (!checkCondition())
     return false;

Also I would prefer to have the positive condition in the if statement, whenever applicable (depending on the length of the blocks):

bool doSomething(){
      if (checkCondition()) {
         // do something
         return true;
      } else {
        return false;
     }
}

You could also drop the else here because of a return in the `if``statement.

bool doSomething(){
      if (checkCondition()) {
         // do something
         return true;
      }
      return false;
}
0
as-if-i-code On

Your code itself is simple and clean. But below is one more clean variation (avoiding explicit true/false)

bool doSomething(){
   var isConditionTrue = checkCondition();

   if (isConditionTrue) 
   {
       // if executes only in case of 'isConditionTrue = true'
       // do something
   }
   return isConditionTrue; 
}
0
Vlad from Moscow On

In most cases I prefer the following approach

bool doSomething()
{
    bool success = checkCondition();

    if ( success )
    {
        // do something
    }

    return success;
}

For example consider a function that appends a node to a singly-linked list in C.

struct Node
{
    int data;
    struct Node *next;
};

int append( struct Node **head, int data )
{
    struct Node *new_node = malloc( sizeof( struct Node ) );
    int success = new_node != NULL;

    if ( success )
    {
        new_node->data = data;
        new_node->next = NULL;

        while ( *head != NULL ) head = &( *head )->next;

        *head = new_node;        
    }

    return success;
}
0
Saeed Sayyadipour On

You can remove the if condition as below:

return checkCondition();

It is enough. This code is simple enough but if the checkCondition() function is not too large, you can define it as an "inline" function to enhance performance:

inline bool checkCondition() {//your code;}