英文:
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;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论