gpt4 book ai didi

coding-style - 断言与返回假?

转载 作者:行者123 更新时间:2023-12-04 16:37:45 27 4
gpt4 key购买 nike

关闭。这个问题是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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com