2

Is it more practical to create a class named say, "Constants.java", and declare all the magic constants being use by the whole program, or put everything in properties file named ScreenMessage.properties? Values returned by Constants.java and in Properties file will be use to find a specific message from the database.

Example:

In Constants.java:

public static final String UNSUCCESSFUL_LOGIN = "MSGID001";

In ScreenMessage.properties:

UNSUCCESSFUL_LOGIN=MSGID001

[Added: 2013-May-18]: Actually, the nature of this question is: if I put the Magic Constants in Constants.java, I can retrieve the constant's value by simply "Constants.UNSUCCESSFUL_LOGIN", but if I use properties file, I am embedding again another constant in the program because of the file name of the properties file, and it is more harder if the properties file is not in the same package than that of the class that will load the values of the properties file.

chrismsawi
  • 145
  • 6
  • Are you talking about all constants in the program, or just your message codes? In the latter case, a properties file is the normal approach. – Duncan Jones May 18 '13 at 06:56
  • @DuncanJones:all constants – chrismsawi May 18 '13 at 06:57
  • If you want to have the ability of changing constants without the need of re-compiling your application, go with the latter (But note that they might be changed by anyone else..) – Maroun May 18 '13 at 06:58

3 Answers3

3

It depends of your need.

Pros and cons :

If you have some a Constants.java, you have access to the type of your constants, which is not the case with a properties file.

On the other side, a properties file can be changed without recompiling...

Here, you seem to need some IDs to retrieve some messages from the database. Those messages are strongly linked to the use cases of your application (specific code around each of your messages). Hence I think you should just use some enums as suggested by Juned Ahsan. They will be easier to refer in your code and you will avoid typos.

Arnaud Denoyelle
  • 29,980
  • 16
  • 92
  • 148
2

Best practice is not to have a Constants.java.

Put the constants near where they have relevance, like the way MAX_VALUE constant is define in the Integer and Long classes.

If you have a few constants of the same "type", like your message example, create an enum for them.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
1

I believe enums are a good and acceptable choice these days to define constants

http://docs.oracle.com/javase/1.5.0/docs/guide/language/enums.html

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136