简体   繁体   English

更好的方式来表达“if false return false”结构

[英]Better way to express “if false return false” construct

In many cases you have code like this (C-style pseudo code used):在许多情况下,您有这样的代码(使用 C 风格的伪代码):

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.有时,条件检查可以留给调用者或断言,但通常条件检查必须在 function 内部完成。

You can get fancy and use exceptions, but result is almost the same code.您可以花哨并使用异常,但结果几乎是相同的代码。

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):我也希望在 if 语句中使用肯定条件,只要适用(取决于块的长度):

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.由于 `if` 语句中的返回,您也可以在此处删除else

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

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; 
}

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.例如,考虑将一个节点附加到 C 中的单链表的 function。

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;
}

You can remove the if condition as below:您可以删除 if 条件,如下所示:

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:这段代码很简单,但如果checkCondition() function 不是太大,您可以将其定义为“内联” function 以提高性能:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM