有没有一种优雅的方法来重命名Java中的布尔值,以提高代码的可读性?

huangapple go评论66阅读模式
英文:

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

问题

以下是您要翻译的代码部分:

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

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

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

如果您需要进一步的帮助,请随时提问。

英文:

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);
	}
}

答案1

得分: 1

作为一种简单的方法,也许为TRUE和FALSE定义常量是可以的?在你的类中像这样定义它们:

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

另外,在Java中你的选择相对有限。你也可以尝试使用枚举:

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

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;
    }
}

huangapple
  • 本文由 发表于 2020年9月3日 01:41:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/63710919.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定