【发布时间】:2020-04-16 22:52:07
【问题描述】:
我正在创建自己的库,例如 Apache Commons DigestUtils 用于学习目的。
在我的update() 方法中,我编写了一个简单的if (something == null) throw new Exception 作为null 检查。
/**
* Performs a digest update for the {@code String} (converted to bytes using the
* UTF-8 standard charsets) with a specific {@code MessageDigest} and returns
* the final digest data.
*
*
* @param messageDigest the {@code MessageDigest} with a specific algorithm to
* process the digest.
*
* @param data the data to digest.
*
* @return the {@code MessageDigest} with the processed update for the digest.
*
* @throws IllegalArgumentException if {@code messageDigest} is {@code null}.
*
* @throws IllegalArgumentException if {@code data} is {@code null}.
*/
public static MessageDigest update(final MessageDigest messageDigest, final String data) {
if (messageDigest == null)
throw new IllegalArgumentException("messageDigest cannot be null");
if (data == null)
throw new IllegalArgumentException("data cannot be null");
messageDigest.update(data.getBytes(StandardCharsets.UTF_8));
return messageDigest;
}
现在我不确定是否应该在必须调用update() 方法的其他方法中编写相同的检查,还是只在该方法抛出相应异常的 cmets 中编写。
public static byte[] digest(final MessageDigest messageDigest, final byte[] data) {
return update(messageDigest, data).digest();
}
或
public static byte[] digest(final MessageDigest messageDigest, final byte[] data) {
if (messageDigest == null)
throw new IllegalArgumentException("messageDigest cannot be null");
if (data == null)
throw new IllegalArgumentException("data cannot be null");
return update(messageDigest, data).digest();
}
注意digest() 方法调用update() 方法。
最佳做法是什么?
【问题讨论】:
标签: java nullpointerexception throw