【问题标题】:Better way to express "if false return false" construct更好的方式来表达“if false return false”构造
【发布时间】:2020-05-09 09:39:08
【问题描述】:

在很多情况下,你有这样的代码(使用 C 风格的伪代码):

bool checkCondition();

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

   // do something
   return true;
}

我不断重复使用这种模式,每次都想知道是否有更好的方式来表达它?

有时,条件检查可以留给调用者或断言,但通常条件检查必须在函数内部完成。

您可以花哨并使用异常,但结果几乎是相同的代码。

【问题讨论】:

  • 更好是什么意思?这是非常简单易读的代码(理想的 imo)。
  • 某些语言有guard 语句用于此目的。 guard 这个词比 if 更能表达这种感觉,不是吗?例如,在 Swift 中你会使用guard checkCondition() else { return false }。但是Java中没有这样的东西。 (不了解 C++)。
  • if ( not condition()) return false; 但你的解决方案也很好
  • @DominikWosiński 您的声明不允许在函数内添加额外代码。
  • 您永远不必使用“== false”或“== true”或“!= false”或“!= true” - 布尔实例本身已经拥有此信息。跨度>

标签: java c++ imperative-programming


【解决方案1】:

首先我会这样表达否定:

 if (!checkCondition())
     return false;

如果适用,我也希望在 if 语句中使用肯定条件(取决于块的长度):

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

您也可以在此处删除 else,因为 `if`` 语句中有返回值。

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

【讨论】:

  • 我认为简单的if (!condition) return false; 更好,因为您不需要任何else 和其他括号。
  • 这取决于“做某事”的长度和您的个人品味。
  • @sanitizedUser 这取决于您想要的详细程度。就我个人而言,我倾向于同意你的观点,但我通常会按照我正在工作的任何代码库的流程进行。无论如何,我们肯定在意见领域。
  • 我在这里添加了另一个变体。我认为,通过“我也更愿意……”的介绍,我清楚地表明我们在这里处于意见领域。像if there is better way to express it? 这样的问题只能有基于意见的答案。它太模糊了,无法得到任何确凿的事实,它只是在寻求替代方案。
【解决方案2】:

您的代码本身既简单又干净。 但下面是一个更干净的变化(避免明确的真/假)

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

   if (isConditionTrue) 
   {
       // if executes only in case of 'isConditionTrue = true'
       // do something
   }
   return isConditionTrue; 
}

【讨论】:

    【解决方案3】:

    在大多数情况下,我更喜欢以下方法

    bool doSomething()
    {
        bool success = checkCondition();
    
        if ( success )
        {
            // do something
        }
    
        return success;
    }
    

    例如,考虑一个将节点附加到 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;
    }
    

    【讨论】:

      【解决方案4】:

      您可以删除 if 条件如下:

      return checkCondition();
      

      够了。这段代码很简单,但如果checkCondition()函数不是太大,你可以将其定义为“内联”函数以提高性能:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多