Java:如何减少无法合并它们的if-else语句的数量

问题描述 投票:0回答:1

尽管我的代码完全按照我的意愿运行,但我的代码中有很多if-else语句,所以我想问一下是否可以减少此代码中的if-else语句

if ( nightPost(timePicker1.getValue().toString(), timePicker4.getValue().toString()) ) {
    if ( !teToTime.isAfter(LocalTime.parse("08:30",format)) ) {
        textField4.setStyle("");
        if(getDifference(timeKA, timeKB)<121 && getDifference(timeKA, timeKB)>59) {
            timePicker3.setStyle("");
            if ( range(timePicker1.getValue().toString(), timePicker2.getValue().toString(),
                timePicker3.getValue().toString(), timePicker4.getValue().toString())) {
                timePicker2.setStyle("");
                timePicker3.setStyle("");
                if( increaseTxt.isBefore(LocalTime.parse("11:01",format)) )
                {
                    textField5.setStyle("");
                    return true;
                } else {
                    textField5.setStyle("-fx-border-color: red");
                    return false;
                }
            } else {
                timePicker2.setStyle("-fx-border-color: orange");
                return false;
            }                               
        }
        else {
            timePicker3.setStyle("-fx-border-color: red");
            return false;
        }
    } else {
        textField4.setStyle("-fx-border-color: red");
        return false;
    }
}
return false;
java if-statement switch-statement conditional
1个回答
3
投票

Guard Clauses替换Nested Conditional

if (!nightPost(timePicker1.getValue().toString(), timePicker4.getValue().toString()) ) {
    return false;
}
if ( teToTime.isAfter(LocalTime.parse("08:30",format)) ) {
    textField4.setStyle("-fx-border-color: red");
    return false;
}
textField4.setStyle("");
if ( !(getDifference(timeKA, timeKB) < 121 && getDifference(timeKA, timeKB) > 59) ) {
    timePicker3.setStyle("-fx-border-color: red");
    return false;
}
timePicker3.setStyle("");
if ( !range(timePicker1.getValue().toString(), timePicker2.getValue().toString(), 
            timePicker3.getValue().toString(), timePicker4.getValue().toString()) ) 
{
    timePicker2.setStyle("-fx-border-color: orange");
    return false;
}
timePicker2.setStyle("");
timePicker3.setStyle("");
if ( !increaseTxt.isBefore(LocalTime.parse("11:01",format)) ) {
    textField5.setStyle("-fx-border-color: red");
    return false;
}
textField5.setStyle("");
return true;
© www.soinside.com 2019 - 2024. All rights reserved.