计算函数返回值的最佳实践 [英] Best practice for compute the function return value

查看:101
本文介绍了计算函数返回值的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常在C语言中构建函数,该函数检查一些参数并返回错误代码.

Often I built functions, in C, that checks some parameters and return an error code.

发现错误后停止值检查的最佳方法是什么?

Which is the best approach to stop the values checking when I found an error?

第一个示例:

ErrorCode_e myCheckFunction( some params )
{
  ErrorCode_e error = CHECK_FAILED;

  if( foo == bar )
  {
     if( foo_1 == bar_1 )
     {
        if( foo_2 == bar_2 )
        {
           error = CHECK_SUCCESS;
        }
     }
  }

  return error;
}

第二个例子:

ErrorCode_e myCheckFunction( some params )
{
  if( foo != bar )
  {
     return CHECK_FAILED;
  }

  if( foo_1 != bar_1 )
  {
     return CHECK_FAILED;
  }

  if( foo_2 != bar_2 )
  {
     return CHECK_SUCCESS;
  }
}

我更喜欢第一种方法,因为我读到MISRA规则避免了多个return语句.

I prefer the first approach because I read that the MISRA rules avoid multiple return statement.

哪种方法最好?

推荐答案

第二个是最好的,因为它非常易于阅读,可以随着复杂性的增加而很好地缩放,并且在出现错误时立即停止执行该函数.当您在函数内部进行大量错误处理时(例如,如果该函数是解析器或协议解码器),这是编写此类函数的唯一明智的方法.

The second is best because it is so much easier to read, scales well with increased complexity and immediately stops executing the function upon errors. This is the only sensible way to write such functions when you have extensive error handling inside a function, for example if the function is a parser or protocol decoder.

MISRA-C不允许在函数中使用多个return语句是MISRA-C的缺陷.据推测,这样做的目的是禁止从各处返回的意大利面条式代码,但是,从我们的示例中可以看出,严格禁止多个return语句实际上会使代码的可读性大大降低.想象一下您是否需要检查10个不同的错误.然后,您将有10个复合if语句,这将是一个难以理解的混乱.

That MISRA-C disallows multiple return statements in a function is a defect of MISRA-C. The intention is supposedly to disallow spaghetti code that returns from all over the place, but dogmatically banning multiple return statements can actually turn code far less readable, as we can see from your example. Imagine if you needed to check 10 different errors. You'd then have 10 compound if statements, which would be an unreadable mess.

我已多次向MISRA委员会报告此缺陷,但他们没有听取.相反,MISRA-C只是盲目地将IEC 61508引用为该规则的来源.依次仅列出了该规则的一个可疑来源(IEC 61508:7 C.2.9),它是1979年的一本恐龙编程书.

I have reported this defect several times to the MISRA committee but they have not listened. Instead, MISRA-C just blindly cites IEC 61508 as source for the rule. Which in turn only lists one questionable source for this rule (IEC 61508:7 C.2.9) and it's some a dinosaur programming book from 1979.

这既不是专业的也不是科学的-MISRA-C和IEC 61508(和ISO 26262)都应该为(直接或间接)将1979年以来的主观废话列为唯一来源和理由感到ham愧.

This is not professional nor scientific - both MISRA-C and IEC 61508 (and ISO 26262) should feel ashamed over (directly or indirectly) listing subjective nonsense from 1979 as their only source and rationale.

仅使用第二种形式并针对此缺陷MISRA规则提出永久偏差.

Simply use the second form and raise a permanent deviation against this defect MISRA rule.

这篇关于计算函数返回值的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆