Java Utility Class vs. Service [closed] Java Utility Class vs. Service [closed] java java

Java Utility Class vs. Service [closed]


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.


The difference is that service classes might have state. And by state I mean conversational state. Consider a notional ordering system.

interface OrderSystem {  void login(String username, String password);  List<Item> search(String criteria);  void order(Item item);  void order(Item item, int quantity);  void update(Item item, int quantity);  void remove(Item item);  void checkout();  Map<Item, Integer> getCart();  void logout();}

Such a thing could be done with stateful session beans (as one example), although in that case authentication would probably be covered more traditional EJB mechanisms.

The point here is that there is conversational state in that the results of one call affects subsequent calls. You could view static methods as a bunch of simple stateless services that execute locally.

A service has a much broader meaning that includes, but is not limited to, being:

  • stateful;
  • remote; and
  • implementation dependent (ie through an interface).

Best practice I think is to simply use static methods as convenience methods (especially given Java's lack of extension methods). Services are much richer than that.


You cannot override static method, which can be a huge problem in case you'd like to implement your service in two different ways and switch between them. For this reason, I would limit the use of static utility classes to simple things which will "never" (for sufficiently long value of "never" :)) need to be done in more than one way.