I'm creating my own library like Apache Commons DigestUtils
for learning purposes.
Inside of my update()
method I've written a simple if (something == null) throw new Exception
as null
checking.
/**
* 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;
}
Now I'm not sure if I should write the same checks in other methods that must call the update()
method, or only write it in the comments that the method throws the corresponding exceptions.
public static byte[] digest(final MessageDigest messageDigest, final byte[] data) {
return update(messageDigest, data).digest();
}
or
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();
}
Note that digest()
method calls update()
method.
What is the best practice?