Why does Java MessageDigest.getInstance() have a String as a parameter?

  softwareengineering

I presume it’s that way so it could be extended with custom algorithms, but wouldn’t it be more convenient to apply, let’s say, factory method pattern here and avoid the whole NoSuchAlgorithmException thing?

Something like:

MessageDigest.getMD5Algorithm();

or

MessageDigest.getInstance(DigestAlgorithmFactory.getMD5Algorithm())

I’m guessing there’s a bigger picture here, but I just can’t see it.

1

MethodDigest.getInstance(String algorithm) is a factory method.

The algorithm param is required. A digest is an abstract concept, there is no default concrete digest but there are lots of different digest implementations.

I presume it’s that way so it could be extended with custom algorithms

Yes, these are done by writing and registering security providers, such as Bouncy Castle. Note that MessageDigest itself knows nothing of the implementations, it simply looks at what security providers are available to see if one of them supports the given algorithm. It may be the case that no provider supports the algorithm, hence why it throws NoSuchAlgorithmException.

8

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT