How to define Constant values - Best Practice

2019-04-25 08:44发布

I have two ways to define constants. First one holds the bunch of static final DataType variables in a class and another by using Enum.

Here is the fist type:

public class TipTipProperties {
    public static final String MAX_WIDTH_AUTO = "auto";
    public static final String POSITION_RIGHT = "right";    
}

And the usage of these variable will via static call, as an example: TipTipProperties.MAX_WIDTH_AUTO

And the second type is:

public enum TipTipProperties {

    MAX_WIDTH_AUTO(MaxWidth.AUTO),  
    POSITION_RIGHT(Position.RIGHT);

    private MaxWidth maxWidth;
    private Position position;  

    private TipTipProperties(MaxWidth maxWidth) {
        this.maxWidth = maxWidth;
    }

    private TipTipProperties(Position position) {       
        this.position = position;
    }

    public MaxWidth getMaxWidth() {
        return maxWidth;
    }   

    public Position getPosition() {
        return position;
    }

    public enum MaxWidth {
        AUTO("auto");

        private String width;

        private MaxWidth(String width) {
            this.width = width;
        }

        public String getWidth() {
            return width;
        }
    }

    public enum Position {
        RIGHT("right"),         

        private String position;

        private Position(String position) {
            this.position = position;
        }

        public String getPosition() {
            return position;
        }       
    }
}

As an example usage: TipTipProperties.POSITION_RIGHT.getPosition().getPosition().

My question is:

  • Which one is better OOP and why?
  • Is there any alternatives or better approach exists?

Thanks in advance.

2条回答
太酷不给撩
2楼-- · 2019-04-25 09:06

Enum is the best to do this as Joshua Bloch said in Effective Java,you will have more control using Enum like if you want to print all constants,you can. with class constants you can not have type safety.read this for further help

查看更多
爷的心禁止访问
3楼-- · 2019-04-25 09:08

Using a properties file in your project would also be a good way of doing this. How to do that in Java is explained at this post.

You could basically create something called tiptip.properties in the root directory of your project and then store all the key-value pairs that you need.

查看更多
登录 后发表回答