Best design pattern to pass needed variable to all code without

392 Views Asked by At

Basically, I have a boolean which is used by like 20% of all my classes on a large API project. Everything, from utility methods to larger classes, uses it. I can set the state (which will not change) on the program start, but don't know the "best" way to access it.

Initially, I went for dependency injection. Quickly, method parameter count grew as almost everything needed it. It was a pain watching the single boolean in almost every parameter in certain classes. I decided to try out a static method. I came up with the following class structure:

public final class MyClass {
    private static boolean neededBoolean;

    public MyClass(boolean bool) {
        MyClass.setBoolean(bool);
    }

    private static void setGems(boolean bool) {
        MyClass.neededBoolean = bool;
    }

    public static boolean getNeededBoolean() {
        return neededBoolean;
    }
}

This felt strange though, most static methods usually don't read internal variables, and any program could easily (purposefully or not) change the variable for everything. I get I could also use a singleton, but I've been told those are best for loggers and other uses, not reading static variables. I also don't want to make the boolean public so any other classes could edit it.

So what's the best choice here? Overusing dependency injection, a singleton, or my current system

1

There are 1 best solutions below

2
On

If you're using a dependency framework, you should absolutely use it.

E.g. if you're using the Spring Framework, you could inject it like this, so the value is initialized from e.g. the application.properties file:

@Component
class MyComponent {
    @Value("${needed.boolean}")
    private boolean neededBoolean;

    // code here that can use the value
}

You might consider using a property configuration object, though, so the property name isn't replicated all over your code. More typo-safe that way.


If you don't have a dependency framework and are ok with calling a static method (tight coupling), and the value is only initialized on startup, I'd suggest a class like this:

public final class AppConfig {
    private static Boolean neededBoolean;

    public void static initialize(boolean neededBoolean) {
        if (neededBoolean != null)
            throw new IllegalStateException("Already initialized");
        AppConfig.neededBoolean = neededBoolean;
    }

    public static boolean getNeededBoolean() {
        if (neededBoolean == null)
            throw new IllegalStateException("Not initialized");
        return neededBoolean;
    }
}