I currently have an object called UserSettings
containing a number of variables of user preferences.
In another class called playerLabels
, I instantiate the object like this:
public static UserSettings settings = new UserSettings();
In a third class, I read from a file and edit the settings object by doing (e.g) playerLabels.settings.setToggled(true);
I have a number of boolean values in the settings file, some of which I want to toggle (switch on->off or off->on). From how I see it, there are three ways to do this:
playerLabels.settings.toggled = !playerLabels.settings.toggled;
playerLabels.settings.setToggled(!playerLabels.settings.getToggled());
- create a toggle method in
settings
for each boolean value
I learned to use setters and getters with java instead of directly accessing the variable which is why I don't want to do the first.
The second is a bit long and feels clumsy however if that's the way to do it that's fine.
The third would be time consuming to create methods for each boolean value.
I have a feeling that my method of storing user preferences isn't ideal, as I'm accessing another unneccessary class (playerLabels) to edit settings. If there is a better way to store variables in the way I want to, that would be helpful.
Thanks
UserSettings:
public class UserSettings {
private boolean toggled = true;
private float height = 0f;
private boolean shadow = true;
private boolean personal = false;
public boolean isToggled() {
return toggled;
}
public void setToggled(boolean toggled) {
this.toggled = toggled;
}
public float getHeight() {
return height;
}
public void setHeight(float height) {
this.height = height;
}
public boolean isShadow() {
return shadow;
}
public void setShadow(boolean shadow) {
this.shadow = shadow;
}
public boolean isPersonal() {
return personal;
}
public void setPersonal(boolean personal) {
this.personal = personal;
}
}
CodePudding user response:
In short you can't without writing a method within the class that holds the private variables. The whole point of creating private variables is to limit the access and thus encapsulate the variables. If you want to toggle it, write a method that uses the getters/settings to toggle it.
CodePudding user response:
If you really want to be lazy and not add a toggle() method for each setting, you can create a new class:
public class ToggleOption {
private boolean value;
public ToggleOption() {}
public ToggleOption(boolean initialValue) {
this.value = initialValue;
}
get() {
return value;
}
set(boolean value) {
this.value = value;
}
toggle() {
this.value = !value;
}
}
In your UserSettings class you then use this new class instead of the boolean flags:
public class UserSettings {
private ToggleOption toggled = new ToggleOption(true);
private float height = 0f;
private ToggleOption shadow = new ToggleOption(true);
private ToggleOption personal = new ToggleOption();
...
}
To toggle, you simply call
playerLabels.settings.getToggled().toggle();