coding-style - 断言与返回假?

标签 coding-style

关闭。这个问题是opinion-based .它目前不接受答案。












想改善这个问题吗?更新问题,以便可以通过 editing this post 用事实和引文回答问题.

4年前关闭。




Improve this question



bool fn()
{
  if(something bad happen)
     return false;
  ..
}


void gn()
{
  assert(something == true);
  ..

}

当我在生产代码中编写一个函数时,我应该用哪种方式
选择?

最佳答案

Assert ,至少在 .NET 中,主要用于测试。其具体用途简明扼要here :

An assertion is best used to test a condition only when all of the following hold:


* the condition should never be false if the code is correct,
* the condition is not so trivial so as to obviously be always true, and
* the condition is in some sense internal to a body of software.

在生产代码中,我推荐第一种方法;或 try/catch如果“坏事”永远不会发生;如果是特殊情况。

如果您有一个应该始终存在或永远不存在的不变量(无论系统状态如何),那么这是 Assert 的一个很好的候选者。除了测试用例。

我在生产代码中看到了断言;通常在 design-by-contract style code .我在单元测试中更频繁地看到它们。

关于coding-style - 断言与返回假?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/920255/

相关文章:

php - 如何正确循环PHP中的数组键

asp.net - HTML 和 CSS 编码指南

objective-c - 在 Obj-C 方法声明中不放置任何空格的约定是如何产生的?

php - 包含内部函数被认为是不好的做法吗?

VIM - 重新格式化缩进和大括号

ruby - 为什么要避免在 Ruby 中使用 then 关键字?

c++ - const int *p 与 int const *p - 类型后的 const 是否可以接受?

python - 将属性重命名为 _property 的原因

javascript - JavaScript 的 eval() 什么时候不是邪恶的?

coding-style - 将尽可能多的逻辑放在最少(一行)代码中的利弊是什么?