Properties or Enums or static final

拜拜、爱过 提交于 2019-12-10 17:55:09

问题


When it comes to declare predefined constants in a name-value pair, I have been randomly choosing between 'java.util.Properties', 'enums' or a separate class with 'public static final' values.

For future reference, I need some guidelines over which approach to take.

Thanks!


回答1:


It all depends of your constant lifecycle. Constant are by definition something that do not move. Choosing the right methods will be a question of the likely to change and the repackaging need.

  • If you're really sure, it wont move ever : static final is the way to go. Pi, mathematical constants, things like that are a good example.

  • If you think there is a potential change but need the ease of code manipulation and do not fear of ascendant compatibility, enums is ok. I did that for error code some time ago.

  • If you think there is a potential change but you don't want this change to impact your code, properties (with resource bundle) is the better choice. Labels (translations), inital settings, etc are also a good example.




回答2:


static final fields are used when you cannot form a definite set of closed options from which you can choose the state of a variable. On the contrary, when you can, you always use enums.

Now, when you want to keep a dictionary of key-values, regardless of their nature, it's time to use a Properties type object or sometimes a Map.




回答3:


One more thing to consider - will these Strings change in different versions? i.e. might you have a French version, a Chinese version, an "advanced" version? If so, Properties / ResourceBundles etc. are the way to go.




回答4:


Use Enums when your set of constants are fixed and not expected to change often. If it often changes then its difficult to maintain backward compatibility with your previous versions. If in a client server architecture both have different versions of some Enum. E.g

Server : public enum Priority{ HIGH,LOW,MEDIUM,AVERAGE}

Client : public enum Priority{ HIGH,LOW,MEDIUM}

Let's say if server sends Priority.AVERAGE to client then the client will throw exception.



来源:https://stackoverflow.com/questions/8864720/properties-or-enums-or-static-final

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!