Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java Properties - to expose or not to expose?

This might be an age old problem and I am sure everyone has their own ways. Suppose I have some properties defined such as

secret.user.id=user
secret.password=password
website.url=http://stackoverflow.com

Suppose I have 100 different classes and places where I need to use these properties. Which one is good (1) I create a Util class that will load all properties and serve them using a key constant Such as : Util is a singleton that loads all properties and keeps up on getInstance() call.

Util myUtil = Util.getInstance();
String user = myUtil.getConfigByKey(Constants.SECRET_USER_ID);
String password = myUtil.getConfigByKey(Constants.SECRET_PASSWORD);
..
//getConfigByKey() - inturns invokes properties.get(..)
doSomething(user, password)

So wherever I need these properties, I can do steps above.

(2) I create a meaningful Class to represent these properties; say, ApplicationConfig and provide getters to get specific properties. So above code may look like:

ApplicationConfig config = ApplicationConfig.getInstance();
doSomething(config.getSecretUserId(), config.getPassword());
//ApplicationConfig would have instance variables that are initialized during
// getInstance() after loading from properties file.

Note: The properties file as such will have only minor changes in the future.

My personal choice is (2) - let me hear some comments?

like image 464
ring bearer Avatar asked Oct 14 '22 08:10

ring bearer


2 Answers

Do it the most straightforward way (a class with static values):

package com.domain.packagename

public class Properties {
    private static String hostName;
    public static getHostName() { return hostName; }
    private static int port;
    public static int getPort() { return port; }

    public static void load() {
        //do IO stuff, probably
        hostName = ??;
        port = ??;
        //etc
    }
}
like image 131
Seun Osewa Avatar answered Oct 19 '22 08:10

Seun Osewa


I find the first approach to be more verbose than necessary. (Especially if the properties are not expected to change very much.) Also, by using the second approach you can handle casting/type issues when the properties are loaded instead of when they are used.

like image 35
Jeremy Avatar answered Oct 19 '22 09:10

Jeremy