[英]Guava preconditions checkNull, checkArgument
I want to check preconditions on a base class so that I know subtypes will always use constructor arguments that are valid. 我想检查基类上的前提条件,以便知道子类型将始终使用有效的构造函数参数。
Let's take as an example a constructor that: 让我们以一个构造器为例:
How would one best use the Guava preconditions approach in that case? 在这种情况下,如何最好地使用番石榴前提条件方法?
In a mock example like this: (this is contrived!) 在这样的模拟示例中:(这是人为的!)
protected AbstractException(String errorMessage, Throwable errorCause) {
super(errorMessage, errorCause);
checkNotNull(errorMessage,
ErrorMessage.MethodArgument.CANNOT_BE_NULL_CHECK, "errorMessage");
checkArgument(!errorMessage.isEmpty(),
ErrorMessage.MethodArgument.CANNOT_BE_EMPTY_STRING_CHECK,
"errorMessage");
checkNotNull(errorCause, ErrorMessage.MethodArgument.CANNOT_BE_NULL_CHECK,
"errorCause");
}
I end up calling super
before checking the arguments because a call to super
needs to be the first line of the method and, although I could do super(checkNoNull(errorMessage))
, I cannot do the same wrapping using checkArgument
because that returns void
. 我最终在检查参数之前调用了
super
,因为对super
的调用需要是方法的第一行,尽管我可以做super(checkNoNull(errorMessage))
,但是我不能使用checkArgument
进行相同的包装,因为这会返回void
。 So the dilemma is: 因此,难题是:
checkStringNotNullAndNotEmpty()
checkStringNotNullAndNotEmpty()
一样“分组”检查 I use the odd-looking ErrorMessage.MethodArgument.CANNOT_BE_NULL_CHECK because the default throw
does not include an error message so from the testing side I cannot recognise this as an argument validation failure rather than a "any" NPE? 我使用外观怪异的ErrorMessage.MethodArgument.CANNOT_BE_NULL_CHECK,因为默认
throw
不包含错误消息,因此从测试方面,我无法将其识别为参数验证失败,而不是“任何” NPE?
Am I doing it all wrong? 我做错了吗?
This should have been a comment, but it's too long. 这本来应该是一个评论,但是太长了。
super
before the test is harmless provided that the super ctor doesn't do things which it shouldn't do anyway . super
是无害的。 More important: The exceptions you're throwing are probably inferior to the ones you'd get without all the checks. 更重要的是:您抛出的异常可能不如没有所有检查的异常。 Imagine the user provides a cause and no message.
假设用户提供了原因,但没有消息。 That's bad, you think, but you replace it with an NPE lacking any cause.
您认为这很糟糕,但是您可以使用没有任何原因的NPE替换它。 That's worse.
更糟
Look at Guava's Preconditions.format
(package private). 查看Guava的
Preconditions.format
(私有包)。 They could check the correct number of arguments first, but they do not. 他们可以先检查正确数量的参数,但不能。 You can provide too few or too many, which is an error, but ignoring it is the best way to handle it.
您可以提供太少或太多,这是一个错误,但忽略它是处理它的最佳方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.