Submerged
Submerged

Reputation: 666

What design pattern should be used for a global configuration

I've been reading that using static variables in a class that's never instantiated is a bad idea, because the variables may turn null when the class is not longer in memory. Makes sense.

This is what I've been doing for an example

public class MasterParameters {

public static boolean           DEBUG_MODE =                true;
protected MasterParameters(){
    // Exists only to defeat instantiation.
}

}

I've also heard using a Singleton is equally bad and people suggest using "dependency injection" -- This seems complicated and overkill for what I need, however. Am I just not looking at the right examples?

I want an easy way to define a variable in one spot that can be accessed from anywhere in my code without having to pass a parameters object around. What do you suggest? Thanks :)

Upvotes: 7

Views: 3843

Answers (2)

Sebastian Łaskawiec
Sebastian Łaskawiec

Reputation: 2737

I would suggest Singleton pattern (I know many people don't like it), but it seems the simplest solution that will work. Take a look at this piece of code:

public enum Constants {
    INSTANCE;

    public void isInDebugMode() { 
        return true;
    }
}

Here is how you use it (even from static code):

if(Constants.INSTANCE.isInDebugMode()) {....}

You might also think about some more sophisticated solution:

public enum Constants {
    DEBUG(true),
    PRINT_VARS(false);

    private boolean enabled;

    private Constants(boolean enabled) {
        this.enabled = enabled;
    }

    public boolean isEnabled() {
        return enabled;
    }
}

Example usage:

if(Constants.DEBUG.isEnabled()) {....}

Upvotes: 4

arc
arc

Reputation: 584

It is best practice to use a static method, instead of a variable:

public class MasterParameters {

public static boolean DebugMode(){
     return true; // change this
}
protected MasterParameters(){
    // Exists only to defeat instantiation.
}

Upvotes: 0

Related Questions