这个问题可能与语言无关,但我将专注于指定的语言。
在处理一些遗留代码时,我经常看到函数的示例,这些函数(在我看来,显然)在它们内部做了太多的工作。我说的不是 5000 个 LoC 怪物,而是关于在它们内部实现先决条件检查的函数。
这是一个小例子:
void WorriedFunction(...) {
// Of course, this is a bit exaggerated, but I guess this helps
// to understand the idea.
if (argument1 != null) return;
if (argument2 + argument3 < 0) return;
if (stateManager.currentlyDrawing()) return;
// Actual function implementation starts here.
// do_what_the_function_is_used_for
}
现在,当调用这种函数时,调用者不必担心要满足的所有先决条件,可以简单地说:
// Call the function.
WorriedFunction(...);
现在 -应该如何处理以下问题?
就像,一般来说 - 这个函数是否应该只做它所要求的并将“先决条件检查”移动到调用方:
if (argument1 != null && argument2 + argument3 < 0 && ...) {
// Now all the checks inside can be removed.
NotWorriedFunction();
}
或者 - 它是否应该在每个先决条件不匹配时简单地抛出异常?
if (argument1 != null) throw NullArgumentException;
我不确定这个问题是否可以一概而论,但我仍然想在这里谈谈你对此的看法——也许我可以重新考虑一些事情。
如果您有其他解决方案,请随时告诉我:)
谢谢你。