Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Utility Class vs. Service [closed]

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?

like image 871
djunforgetable Avatar asked May 16 '09 01:05

djunforgetable


People also ask

What is a Java utility class?

A utility class is a class that is just a namespace for functions. No instances of it can exist, and all its members are static. For example, java. lang. Math and java.

Why do we use utility class in Java?

utility class is a class that defines a set of methods that perform common, often re-used functions. Most utility classes define these common methods under static (see Static variable) scope. Examples of utility classes include java.

What is the difference between helper and service?

Service able to serve some clients, and often this is a SOA specific entity. Helper provides a set of methods which commonly are pure functions.

Should utility classes be static Java?

Pure utility classes should usually be static. When you have a class with well-defined input and output, no side effects and no state, then by definition it should be a static class.


1 Answers

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.

like image 178
erickson Avatar answered Sep 27 '22 21:09

erickson