简体   繁体   中英

Utility class alternative for private static field

import java.io.File;

public final class MultiplatformUtility {
    private static final String SEPARATOR = File.separator;

    private MultiplatformUtility() { }

    public static String getSeparator() {
        return SEPARATOR;
    }
}

I want SEPARATOR to be in a unique file. Is there a way to avoid using a utility class here but maintain SEPARATOR field static and private?

Edit: How about a ENUM inside of a Class?

import java.io.File;

public class Multiplatform {

    public enum Common {
        SEPARATOR(File.separator);
    
        private final String separator;

        Common(final String separator) {
            this.separator = separator;
        }

        public String getSeparator() {
            return separator;
        }
    }
}

In my humble opinion, it doesn't make sense to make SEPARATOR as private , considering also that is a public member of java.io.File , so you are restricting the access qualifier of an already existing field. That is against the encapsulation and inheritance best practice.

Bear in mind that when you make it private , only that class will have access to its value, unless you provide a specific method to get access to it, just as you did with MultiplatformUtility .
As possible solution to your goal, you could have a public abstract class in a separated file, and make the field protected, so only the classes which extends your abstract class will have access to it. Personally, this is NOT best practice.

Normally, you define an interface and add all constants in it, so it can be used by all classes among your application, but in that case each constant will be by default public static final .

Even better, you can define an enum in a sepated class, just as in your example, which gives you also more advantages than an interface as you get some utility functions by the fact that implicitly extends java.lang.Enum , plus you can define fields, methods and implement interfaces.

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