Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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.

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

1 Answer 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.

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
1  
@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

 
discard

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.