1

When I am creating static utilities method, I always go with the below logic.

public class XXXUtils {
    // to prevent utilities class accidentally instantiated
    private XXXUtils() {}

    public static XXX getXXX(YYY yyy) {
        // ...
    }
}

which I think is the de-facto standard, and is used by jdk (e.g. java.util.Collections), guava (e.g. com.google.common.collect.Collections2).

However today when I am browsing the SpringMVC source code, I found that utilities class are created in the following.

public abstract class XXXUtils {
    public static XXX getXXX(YYY yyy) {
        // ...
    }
}

This is found in SpringWeb org.springframework.web.context.support.WebApplicationContextUtils. This is an interesting idea that I did not think of previously.

And of course, both mechanism works well for disallowing the instance from initializing. But which way is a better way of creating utilities class that only contains static field and methods. and Why?

CHANist
  • 1,302
  • 11
  • 36
  • None. You can always extend a `public` `abstract` class with a non-_protected_ constructor (if no ex). As an alternative, put your utilities in a non-extensible empty `enum` (why?). Or better consider creating a `final` class instead with a `private` constructor throwing an `AssertionError` in case someone attempts to instantiate a utility class using reflection (does not applies to using the `Unsafe` class to instantiate objects without constructors if I recall correctly). The latter approach is also used by Lombok `@UtilityClass`: https://projectlombok.org/features/experimental/UtilityClass – terrorrussia-keeps-killing Dec 21 '21 at 05:08
  • 1
    Duplicate of https://stackoverflow.com/questions/20593278 ? – Stephen C Dec 21 '21 at 05:49
  • Yes, thanks. I will close the question, would referencing to that question. – CHANist Dec 21 '21 at 06:59

0 Answers0