Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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:




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

share|improve this question
If you had something like MessageDigest.getMD5Algorithm(); then the class would have to be updated everytime it needed to support a new algorithm, and there are a lot of algorithms. – Qwerky Jan 4 '13 at 12:14

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.

share|improve this answer
Why wouldn't getInstance() accept a provider interface implementation explicitly? Why is it better to relay on a String designator? – cbaby Jan 4 '13 at 12:15
Yes, but you still have to tell it which algorithm to use by string. So, why not accept an algorithm directly or something. I still find it hard to believe that there's no safer way to do this. – cbaby Jan 4 '13 at 12:21
@cbaby What's unsafe about it? – James Jan 4 '13 at 17:35
@cbaby because the current strategy will probably allow new digest algorithms to be made available without any need for recompilation, plugins if you like. So if you invent "CBabyDigest" you can use it merely by installing it on your system and also distribute it to others. (I've no idea what goes on under the hood.) – James Jan 4 '13 at 18:37

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.