Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Utility class in Spring application - should I use static methods or not?

People also ask

Should utility methods be static?

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.

What type of methods are used by a utility class?

Utility Class, also known as Helper class, is a class, which contains just static methods, it is stateless and cannot be instantiated. It contains a bunch of related methods, so they can be reused across the application. As an example consider Apache StringUtils, CollectionUtils or java. lang.

Why utility methods are static in java?

Static methods are utility methods defined in a class that do not fit the tradition method- receiver pattern. Static methods are used where there is not a natural choice of a receiver object for the problem the method solves.

When should static methods be used?

Static methods are usually preferred when: All instance methods should share a specific piece of code (although you could still have an instance method for that). You want to call method without having to create an instance of that class. You must make sure that the utility class is never changed.


I don't think so. A DateUtils class sounds like a pure utility class that doesn't have any side effects but just processes input parameters. That kind of functionality may as well remain in a static method. I don't think it's very likely that you'll want to mock date helper methods.


I agree with Sean Patrick Floyd.

This is my criterion: if the methods of the class do things only over the parameters they receive, with no external dependencies (database, file system, user config, other objects/beans, etc.), then I would do it with static methods, usually in a final class with a private constructor.

Otherwise, I would implement it using a Spring bean.

So, in the case that you raise, according to this criterion, I would write a class with static methods.

Regards.


It would be better to declare it as a Spring bean because the life cycle of it is then managed by Spring, and you can eventually inject dependencies, pool the object, as well as test it in a proper way, not to talk that you could use it as a regular object and pass it as parameter, redefine the method in subclasses... etc.

In short, yes it would be a better design in most cases. Nevertheless, in a case as simple as the exposed, it doesn't do a great difference.