字符串类的接口通常具有名为IsEmpty(VCL)或empty(STL)的方法.这是绝对合理的,因为它是一个特殊情况,但使用这些方法的代码通常必须否定这个谓词,这导致"光学(甚至心理)开销"(感叹号不是很明显,特别是在一个左括号后) ).例如,请参阅此(简化)代码:
/// format an optional time specification for output
std::string fmtTime(const std::string& start, const std::string& end)
{
std::string time;
if (!start.empty() || !end.empty()) {
if (!start.empty() && !end.empty()) {
time = "from "+start+" to "+end;
} else {
if (end.empty()) {
time = "since "+start;
} else {
time = "until "+end;
}
}
}
return time;
}
Run Code Online (Sandbox Code Playgroud)
它有四个否定,因为空案例是要跳过的.在设计界面时,我经常会观察到这种否定,这不是一个大问题,但它很烦人.我只想支持编写易于理解且易于阅读的代码.我希望你能理解我的观点.
也许我只是失明了:你如何解决上述问题?
编辑:在阅读了一些评论后,我认为原始代码使用System::AnsiString …