我已经大量使用这些 sn-ps,寻找 null 值和空字符串。
我使用“参数测试”模板作为方法中的第一个代码来检查接收到的参数。
testNullArgument
if (${varName} == null) {
throw new NullPointerException(
"Illegal argument. The argument cannot be null: ${varName}");
}
您可能希望更改异常消息以符合您公司或项目的标准。但是,我确实建议您使用一些包含违规参数名称的消息。否则,您的方法的调用者将不得不查看代码以了解出了什么问题。 (没有消息的NullPointerException 会产生一个异常,带有相当荒谬的消息“null”)。
testNullOrEmptyStringArgument
if (${varName} == null) {
throw new NullPointerException(
"Illegal argument. The argument cannot be null: ${varName}");
}
${varName} = ${varName}.trim();
if (${varName}.isEmpty()) {
throw new IllegalArgumentException(
"Illegal argument. The argument cannot be an empty string: ${varName}");
}
您还可以重用上面的空值检查模板并实现此 sn-p 以仅检查空字符串。然后,您将使用这两个模板来生成上述代码。
然而,上面的模板有一个问题,如果 in 参数是最终的,您将不得不修改生成的代码(${varName} = ${varName}.trim() 将失败)。
如果您使用大量最终参数并希望检查空字符串,但又不必将它们作为代码的一部分进行修剪,则可以改为:
if (${varName} == null) {
throw new NullPointerException(
"Illegal argument. The argument cannot be null: ${varName}");
}
if (${varName}.trim().isEmpty()) {
throw new IllegalArgumentException(
"Illegal argument. The argument cannot be an empty string: ${varName}");
}
testNullFieldState
我还创建了一些 sn-ps 来检查未作为参数发送的变量(最大的区别是异常类型,现在改为 IllegalStateException)。
if (${varName} == null) {
throw new IllegalStateException(
"Illegal state. The variable or class field cannot be null: ${varName}");
}
testNullOrEmptyStringFieldState
if (${varName} == null) {
throw new IllegalStateException(
"Illegal state. The variable or class field cannot be null: ${varName}");
}
${varName} = ${varName}.trim();
if (${varName}.isEmpty()) {
throw new IllegalStateException(
"Illegal state. The variable or class field " +
"cannot be an empty string: ${varName}");
}
testArgument
这是测试变量的通用模板。我花了几年的时间才真正学会欣赏这个,现在我经常使用它(当然要结合上面的模板!)
if (!(${varName} ${testExpression})) {
throw new IllegalArgumentException(
"Illegal argument. The argument ${varName} (" + ${varName} + ") " +
"did not pass the test: ${varName} ${testExpression}");
}
您输入一个变量名称或一个返回值的条件,后跟一个操作数(“==”、“”等)和另一个值或变量,如果测试失败,结果代码将抛出一个 IllegalArgumentException。
if 子句稍微复杂,整个表达式用“!()”包裹的原因是为了可以在异常消息中重用测试条件。
也许这会让同事感到困惑,但前提是他们必须查看代码,如果您抛出此类异常,他们可能不必查看...
这是一个数组示例:
public void copy(String[] from, String[] to) {
if (!(from.length == to.length)) {
throw new IllegalArgumentException(
"Illegal argument. The argument from.length (" +
from.length + ") " +
"did not pass the test: from.length == to.length");
}
}
您可以通过调用模板并输入“from.length”[TAB]“== to.length”来获得此结果。
结果比“ArrayIndexOutOfBoundsException”或类似的更有趣,实际上可能让您的用户有机会找出问题。
享受吧!