I'm writing a small java game and am storing global game settings in a class structure like the one below:
public class Globals {
    public static int tileSize = 16;
    public static String screenshotDir = "..\\somepath\\..";
    public static String screenshotNameFormat = "gameNamexxx.png";
    public static int maxParticles = 300;
    public static float gravity = 980f;
    // etc
}
While this is very convenient to work with I'd like to know if this is the accepted pattern.
Store it in a .properties file.
config.properties
tile.size=16
screenshot.dir=..\\somepath\\..
Reading it
// Make sure this happens only the first time you start your application
Properties properties = new Properties();
// You can use FileInputStream, ClassLoader.getResourceAsStream or a reader too
properties.load(...)
Using it
int tileSize = Integer.valueOf(properties.getProperty("tile.size"));
String screenshotDir = properties.getProperty("screenshot.dir");
To simplify things, and to keep your changes minimal, you can also do something like this:
public class Globals {
    private static final Properties properties = new Properties();
    static {
        // do the loading here
    }
    public static final int TILE_SIZE = 
        Integer.valueOf(properties.getProperty("tile.size"));
    public static final String SCREENSHOT_DIR = 
        properties.getProperty("screenshot.dir");
    // etc
}
                        If it really is a small application, it will do. It's not ideal but there's no point bringing in too much sophistication on a small scale.
But read those values from a properties file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With