更好的表达 "if false return false "结构的方式。

问题描述 投票:0回答:2

在很多情况下,你都有这样的代码(使用了C式伪代码)。

bool checkCondition();

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

   // do something
   return true;
}

我一直在重复使用这个模式,每次都在想,是否有更好的方式来表达它?

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

你可以搞得很花哨,使用异常,但结果几乎是一样的代码。

java c++ imperative-programming
2个回答
2
投票

首先我会这样表达否定式。

 if (!checkCondition())
     return false;

另外,我更倾向于在if语句中加入阳性条件,只要适用(取决于块的长度)。

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

你也可以去掉 else 这里是因为`if``statement中的返回。

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

0
投票

你的代码本身就很简单和干净,但下面是一个更干净的变化(避免显式truefalse)。

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

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

0
投票

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

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

0
投票

你可以像下面那样去掉if条件。

return checkCondition();

这就够了 这段代码非常简单,但是如果 checkCondition() 函数不大,你可以将其定义为 "内联 "函数,以提高性能。

inline bool checkCondition() {//your code;}
© www.soinside.com 2019 - 2024. All rights reserved.