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 :)
A singleton pattern ensures that you always get back the same instance of whatever type you are retrieving, whereas the factory pattern generally gives you a different instance of each type. The purpose of the singleton is where you want all calls to go through the same instance.
The Singleton Design Pattern That prevents multiple instances from being active at the same time which could cause weird bugs. Most of the time this gets implemented in the constructor. The goal of the singleton pattern is typically to regulate the global state of an application.
Factory Design Pattern One of the most popular design patterns used by software developers is a factory method. It is a creational pattern that helps create an object without the user getting exposed to creational logic.
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()) {....}
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