简化此代码:if-else

时间:2017-01-18 12:20:42

标签: java

我有这段代码,我想知道是否有办法简化重复的if语句:

convertedImgStr = getConvertedImage();

if (convertedImgStr.contains("::::::::::") || convertedImgStr.contains("null")) {
    if (convertedImgStr.contains("::::::::::")) {
        VIEW.updateStatus(STS_WARNING_IMG);
        LOG.warn("Converter might have failed to transform the image correctly");
    }

    if (convertedImgStr.contains("null")) {
        VIEW.updateStatus(STS_FAILURE_IMG);
        LOG.warn("Converter failed to transform the image");
    }
} else {
    VIEW.updateStatus(STS_SUCCESS_IMG);
}

4 个答案:

答案 0 :(得分:3)

最简单的方法是:

if (convertedImgStr.contains("::::::::::")) {
    VIEW.updateStatus(STS_WARNING_IMG);
    LOG.warn("Converter might have failed to transform the image correctly");
} else if (convertedImgStr.contains("null")) {
    VIEW.updateStatus(STS_FAILURE_IMG);
    LOG.warn("Converter failed to transform the image");
} else {
    VIEW.updateStatus(STS_SUCCESS_IMG);
}

如果是某种方法,请尝试这样:

if (!convertedImgStr.contains("::::::::::") && !convertedImgStr.contains("null")) {
    VIEW.updateStatus(STS_SUCCESS_IMG);
    return;
}
if (convertedImgStr.contains("::::::::::")) {
    VIEW.updateStatus(STS_WARNING_IMG);
    LOG.warn("Converter might have failed to transform the image correctly");
    return;
}
VIEW.updateStatus(STS_FAILURE_IMG);
LOG.warn("Converter failed to transform the image");
(...)

您还可以尝试使用java8的一些技巧:

Status status = Optional.ofNullable(convertedImgStr).filter(str -> str.equals(":::::::::").map(str -> STS_WARNING_IMG);
status = Optional.ofNullable(convertedImgStr).filter(str -> str.equals("null").map(str -> STS_FAILURE_IMG);
if (Objects.isNull(status)) {
    status = STS_SUCCESS_IMG;
}

VIEW.updateStatus(状态); LOG.warn(...)

如果是j8,您还可以进行更多变化。

答案 1 :(得分:1)

您不需要嵌套该语句,else if是您的朋友。

convertedImgStr = getConvertedImage();

if (convertedImgStr.contains("::::::::::")) { 
    VIEW.updateStatus(STS_WARNING_IMG);
    LOG.warn("Converter might have failed to transform the image correctly");
} else if(convertedImgStr.contains("null")) {
    VIEW.updateStatus(STS_FAILURE_IMG);
    LOG.warn("Converter failed to transform the image");
} else {
    VIEW.updateStatus(STS_SUCCESS_IMG);
}

出于兴趣,您是在寻找null作为字符串文字,还是在检查字符串是否 null?如果是后者,那么你会以错误的方式解决它,你需要这样做:

} else if(convertedImgStr == null) {

答案 2 :(得分:1)

尝试下面更简单的代码

if (convertedImgStr.contains("::::::::::")) {  
    updateStatus(STS_WARNING_IMG,"Converter might have failed to transform the image correctly");
}

elsif (convertedImgStr.contains("null")) {
    updateStatus(STS_FAILURE_IMG,"Converter failed to transform the image");
}

else {
updateStatus(STS_SUCCESS_IMG,"");
}

public void updateStatus(String constant,String logMessage){
    VIEW.updateStatus(constant);
    LOG.warn(logMessage);
}

答案 3 :(得分:0)

In write.dta(r_data, file = "r_data.dta") :
  character strings of >244 bytes in column 3 will be truncated