Java Utility Class vs. Service

djunforgetable picture djunforgetable · May 16, 2009 · Viewed 29.7k times · Source

What's the difference in Java between a utility class (a class with static methods) and a Service class (a class with public methods that provides a "service"). For example, one can argue that a cryptographic object (providing methods to encrypt, decrypt, hash or get a salt value) is a Service provider, but many group this functionality into a Utility class with static methods, like CryptoUtil.encrypt(...). I'm trying to figure out which way follows better "design". Thoughts?

Answer

erickson picture erickson · May 16, 2009

Different behaviors can be obtained by using different service objects. Static methods in a utility class can't be swapped out. This is extremely useful for testing, changing implementations, and other purposes.

For example, you mention a CryptoUtil with an encrypt method. It would extremely useful to have different objects that could support different encryption strategies, different message recipients, etc.