简体   繁体   中英

What should the declaration of a helper class, with only static methods, be?

I've got a class here, that only contains static methods, so I call it a helper class, an example:

public class FileUtils {
    public static String readFileEntry(final Path path, final String entryKey) throws IOException { }

    public static String readAndModifyFileEntry(final Path path, final String entryKey, final UnaryOperator<String> operator) throws IOException { }
}

How should I declare the class ( abstract , final , static , etc.), such that it is not possible to instantiate the class? As you are not supposed to do so.
If that is not possible, then what is the best practice?

I'm using Java 8 if that is of any extra help.

You can declare the constructor as private and use the final keyword to prevent extensions :

public final class FileUtils {
    private FileUtils() {
    }

    public static String readFileEntry(final Path path, final String entryKey) throws IOException { }

    public static String readAndModifyFileEntry(final Path path, final String entryKey, final UnaryOperator<String> operator) throws IOException { }
}

This is a common pattern:

public final class Helper {

    private Helper() {}

}

I'd make the class final just as a precaution, so no body extends by mistake. More importantly, I'd add a private constructor so it can't be instantiated:

public final class FileUtils {

    /** Empty private constructor, just to prohibit instantiation */
    private FileUtils() {}

    // Rest of the class...
}

static modifier is relevant for inner classes only and does not prevent its instantiation. final modifier prevents extension of class but does not affect ability to create instances. abstract modifier indeed prevents creating instances of the class. It can be a good practice to mark pure utility classes as abstract . Other way to prevent instanitation of class is to create private constructor:

public class FileUtils {
    private FileUtils() {
        // empty constructor needed just to make it impossible to write new FileUtils()
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM