Search code examples
javabooleanreadability

Is there an elegant way to rename Java boolean values to improve the readability of my code?


Say I have the following (Java 8) code:

private void toggleNewUser() {
    if (ToggleButton.isOn()) {
        fadeLabel(true);
        transitionButtons(true);
    }
    else {
        fadeLabels(false);
        transitionButtons(true);
    }
}

My fadeLabel and transitionButtons functions switch between fading and transitioning in and out, and they do so when the boolean are true and false respectively. But I would like to replace true and false with "in" and "out" to improve the readability of my code. Is there any elegant way to do so?

The only way I could come up with is kind of clunky and not really elegant:

private void toggleNewUser() {

    boolean in = ToggleButton.isOn();
    boolean out = ToggleButton.isOn();

    if (ToggleButton.isOn()) {
        fadeLabel(in);
        transitionButtons(in);
    }
    else {
        fadeLabels(out);
        transitionButtons(out);
    }
}

Solution

  • As a simple way, maybe defining constants for TRUE and FALSE is fine? Define them in your class like:

    public static final boolean IN = true;
    public static final boolean OUT = false;
    

    Otherwise you're pretty limited with Java. You could also try enum:

    public enum Anim {
        IN(true),
        OUT(false);
         
        public final boolean state;
         
        private Element(boolean state) {
            this.state = state;
        }
    }