我喜欢 Asserts 和代码的可读性,但不喜欢代码重复,在几个地方我使用 Debug.Assert 来检查相同的条件,如下所示:
Debug.Assert(kosherBaconList.SelectedIndex != -1, "An error message along the lines - you should not ever be able to click on edit button without selecting a kosher bacon first.");
这是对实际错误的回应,尽管实际列表不包含犹太培根。无论如何,我可以想到两种方法:
private static readonly mustSelectKosherBaconBeforeEditAssertMessage =
"An error message along the lines - you should not ever be able to " +
"click on edit button without selecting a something first.";
...
Debug.Assert(
kosherBaconList.SelectedIndex != -1,
mustSelectKosherBaconBeforeEditAssertMessage)
或:
if (kosherBaconList.SelectedIndex == -1)
{
AssertMustSelectKosherBaconBeforeEdit();
}
...
[Conditional("DEBUG")]
private void AssertMustSelectKosherBaconBeforeEdit()
{
// Compiler will optimize away this variable.
string errorMessage =
"An error message along the lines - you should not ever be able to " +
"click on edit button without selecting a something first.";
Debug.Assert(false, errorMessage);
}
或者是否有第三种方式比上述任何一种方式都更糟糕?请分享。 也欢迎一般有用的相关提示。
请您参考如下方法:
使用第一个(重复的)形式。
原因是:
工作少了。断言仅用于调试,因此重复不会给发布版本增加任何低效率。当代码已经完全可读且功能正常时,不要浪费时间尝试使代码“漂亮”或“优雅”。
我认为它实际上比您的替代方案更短、更易读且更易于维护。
当您在调试器中点击断言时,在代码中包含完整消息非常有用,这样您就可以了解断言的含义。许多程序员使用 Assert(kosherBaconList.SelectedIndex != -1);完全没有任何解释,如果您编写了代码,这很好,但是当您点击别人的断言时,您不知道它意味着。也就是说,我知道我称你的方法为“错误”,但我到底需要修正什么才能称其为“正确”?因此断言消息应该指出问题是什么,以及盯着 Assert() 调用的人需要做什么来修复它。当调试器在测试运行中途停止时,您希望它就在您面前。
有时您会发现添加与触发断言的上下文相关的附加信息很有用,这样您就不必实际调试代码来确定 3 个“相同”断言中的哪一个失败的。出于这个原因,我经常使用断言文本,例如“BaconManager.Cook:您必须选择...”和“BaconManager.Wrap:您必须选择...”。
如果您在 Assert 调用中包含文本,它将不会被编译到您的发布版本中。但是,一旦将其设为静态变量,您就会在发布版本中包含(未使用的)字符串,从而使调试垃圾堵塞它。
如果您想检查多个条件来测试对象的有效性,则可以使用子例程,即
[Conditional("DEBUG")]
private void AssertValidity()
{
Debug.Assert(kosherBaconList.SelectedIndex != -1, "Nothing selected in kosher bacon list");
Debug.Assert(kosherBaconList.COunt > 0, "kosher bacon list is empty!");
}
