gpt4 book ai didi

java - 验证私有(private)帮助器方法的参数

转载 作者:行者123 更新时间:2023-11-30 03:14:20 29 4
gpt4 key购买 nike

我正在阅读 J. Bloch 的《Effective Java》,现在正在阅读有关验证方法参数的部分。他说了以下的话:

For an unexported method, you as the package author control the circumstances under which the method is called, so you can and should ensure that only valid parameter values are ever passed in. Therefore, nonpublic methods should generally check their parameters using assertions.

这是书中的示例:

// Private helper function for a recursive sort
private static void sort(long a[], int offset, int length) {
assert a != null;
assert offset >= 0 && offset <= a.length;
assert length >= 0 && length <= a.length - offset;
// Do the computation
}

我不明白强调的句子如何暗示确保参数值有效。而且,我咨询了JLS 14.10并发现了这个:

An assertion is either enabled or disabled. [...] If the assertion is disabled, execution of the assertion has no effect whatsoever.

我从未在代码中使用过断言语句,因此对我来说,它似乎很容易出错,因为如果断言被禁用,则可能会导致出现难以检测到的错误。他还这样说:

你不能澄清一下他所说的要点吗?

我的意思是,为什么我们不对公共(public)方法也使用 assert 呢?

最佳答案

我认为断言的主要用途应该是检测程序中的错误,以便您能够修复它们。

需要注意的是,它们可以启用禁用。如果您使用 public 方法来验证参数,则您希望它们忽略断言 - public 方法的参数检查应该是 总是完成(当然,如果需要的话)。

还有一点需要注意,断言并不提供信息,由于断言错误可以检索到的消息是:

AssertionFailedException ...

这不像抛出信息性异常来指示错误是什么以及原因那样有用,这对调用者非常有帮助。

关于java - 验证私有(private)帮助器方法的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32985031/

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