utility classes in openmrs-core not final or with public constructor

Hi there!

I’ve stumbled on a few utility classes (that have only static methods, and are not supposed to be instantiated). We state in the javadocs, that its a utility class and sometimes “do not instantiate” but this doesnt prevent anyone.

Do we want to change that? Or at least from now on promote the kind of style like in java.util.Objects:

public final class Objects {
private Objects() {
    throw new AssertionError("No java.util.Objects instances for you!");
}

?

Changing existing might be problematic since who knows if these classes have been extended, instantiated.

But it can definitely be a good practice added to https://wiki.openmrs.org/display/docs/Java+Conventions

Having a convention of preventing instantiation and extension sends a correct message to the user of the utility class. :slight_smile:

1 Like

If a class only has static methods, even if a developer created an instance of it, it would be pointless since there would be no useful instance methods on it to call, isn’t that enough to prevent instantiation?

Personally I think this gets to the point of over-specifying conventions. Adding this would make our conventions marginally longer to read (and thus make people marginally less likely to read them all), without giving us significant benefits.

FYI I recall one place in the code where I had to instantiate something that should be purely static, because that was the most convenient way to make its static methods easily accessible from groovy templates.

How about two sets of conventions? The most and not so important. :slight_smile:

No, it doesn’t prevent instantation. You still can invoke static methods from an instance. The opposite is not true.