gpt4 book ai didi

java - 比多次 if (){do} 检查更优雅的代码

转载 作者:行者123 更新时间:2023-12-01 10:44:24 25 4
gpt4 key购买 nike

结合三个标准,可以通过更优雅的解决方案来实现以下行为吗?如果读了很多,switch case 就会有难闻的气味,否则就会嵌套。

    @Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Switch sr = (Switch) findViewById(R.id.switch_ros);
Switch srs = (Switch) findViewById(R.id.switch_ros_stream);
boolean wifi_state = isConnected(this);
if (buttonView.getId() == R.id.switch_ros & buttonView.isChecked() & wifi_state) {
Toast.makeText(this, "ros intent ready", Toast.LENGTH_SHORT).show();
}
if (buttonView.getId() == R.id.switch_ros & buttonView.isChecked() & !wifi_state) {
Toast.makeText(this, "log: wifi bad", Toast.LENGTH_SHORT).show();
sr.setChecked(false);
}
if (buttonView.getId() == R.id.switch_ros & !buttonView.isChecked()) {
Toast.makeText(this, "ros intent stopped", Toast.LENGTH_SHORT).show();
srs.setChecked(false); // and stop ros intent, automatically calls onCheckedChange again
}
if (buttonView.getId() == R.id.switch_ros_stream & buttonView.isChecked() & sr.isChecked()) {
Toast.makeText(this, "stream intent ready", Toast.LENGTH_SHORT).show();
}
if (buttonView.getId() == R.id.switch_ros_stream & buttonView.isChecked() & !sr.isChecked()) {
Toast.makeText(this, "log: first switch is off", Toast.LENGTH_SHORT).show();
srs.setChecked(false);
}
if (buttonView.getId() == R.id.switch_ros_stream & !buttonView.isChecked()) {
Toast.makeText(this, "stream intent stopped", Toast.LENGTH_SHORT).show();
// and stop stream intent
}
}

最佳答案

我会将它们推出到一个枚举中。这是为您完成的前两个。

enum Check {

IntentReady {

@Override
boolean check(CompoundButton buttonView, boolean wifi_state) {
return buttonView.getId() == R.id.switch_ros & buttonView.isChecked() & wifi_state;
}

@Override
void apply(Switch sr, Switch srs) {
Toast.makeText(this, "ros intent ready", Toast.LENGTH_SHORT).show();
}

},
WIFIBad {

@Override
boolean check(CompoundButton buttonView, boolean wifi_state) {
return buttonView.getId() == R.id.switch_ros & buttonView.isChecked() & !wifi_state;
}

@Override
void apply(Switch sr, Switch srs) {
Toast.makeText(this, "log: wifi bad", Toast.LENGTH_SHORT).show();
sr.setChecked(false);
}

};

abstract boolean check(CompoundButton buttonView, boolean wifi_state);

abstract void apply(Switch sr, Switch srs);
}

public void onCheckedChangedNew(CompoundButton buttonView, boolean isChecked) {
Switch sr = (Switch) findViewById(R.id.switch_ros);
Switch srs = (Switch) findViewById(R.id.switch_ros_stream);
boolean wifi_state = isConnected(this);
for ( Check c : Check.values()) {
if ( c.check(buttonView, wifi_state)) {
c.apply(sr, srs);
}
}
}

这里的主要好处是您可以自动转换代码。完成后,您将拥有更大的灵 active 和清晰度。

关于java - 比多次 if (){do} 检查更优雅的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34265325/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com