如何避免 if else 语句并将它们重写为更小更清晰的代码?

How can avoid if else statements and rewrite them into smaller and cleaner code?

我应该以 yyyy"mm""dd, while using " / ", "." 或 "-" 作为分隔符的形式插入一个参数。该程序确定使用了哪个分隔符,其他功能不相关。然而,有太多的 if else 语句我确信可以用更干净的代码重写或替换。 有什么建议吗?

static String[] weekDays = new String[] {
        "Sun", "Mon", "Tues", "Wednes", "Thurs", "Fri", "Satur"
};

enum weekDays {SUN,MON,TUES,WEDNES,THURS,FRI,SATUR};

static void setCalendarDate(final Calendar cal, final String date, final String seperator) {
    final String[] splitDate = date.split(seperator);
    cal.set(parseInt(splitDate[0]), parseInt(splitDate[1]) - 1, parseInt(splitDate[2]));
}

public static void main(final String[] args) {

    final Calendar cal = Calendar.getInstance();
    if (args.length != 0) {
        if (args[0].contains("-")) {
            setCalendarDate(cal, args[0], "-");
        } else if (args[0].contains("/")) {
            setCalendarDate(cal, args[0], "/");
        } else if (args[0].contains(".")) {
            setCalendarDate(cal, args[0],".");
        }
    }
    final int weekDay = cal.get(Calendar.DAY_OF_WEEK);
    System.out.printf("%sday\n", weekDays[weekDay - 1]);
}

}

就我个人而言,我会像这样存储一个有效分隔符数组:

static final String[] validSeparators = new String[] {"-","/","."};

您可以将分隔符检查移至 setCalendarDate 方法本身,检查字符串是否包含任何适当的字符。然后我将重构方法以在无效分隔符上抛出异常,并删除分隔符参数。

static void setCalendarDate(final Calendar cal, final String date) throws ParseException{
    String separator = null;
    for(String s : validSeparators) {
        if(date.contains(s)) {
            separator = s;
            break;
        }
    }
    if(separator == null) {
        throw new ParseException("No valid separator found", 0);
    }

    final String[] splitDate = date.split(separator);
    cal.set(Integer.parseInt(splitDate[0]), Integer.parseInt(splitDate[1]) - 1, Integer.parseInt(splitDate[2]));
}

另一种选择是检查日期字符串的特定字符:

static void setCalendarDate(final Calendar cal, final String date) throws ParseException{       
    String separator = String.valueOf(date.charAt(4));
    if(Arrays.asList(validSeparators).contains(separator)) {
        final String[] splitDate = date.split(separator);
        cal.set(Integer.parseInt(splitDate[0]), Integer.parseInt(splitDate[1]) - 1, Integer.parseInt(splitDate[2]));
    } else {
        throw new ParseException("Valid separator not found", 0);
    }
}

如果你想要额外的安全,你也可以检查第 7 个字符并在拆分之前比较它们。

最后,您的 main 现在看起来像这样:

final Calendar cal = Calendar.getInstance();
if (args.length != 0) {

    try {
        setCalendarDate(cal, args[0]);
    } catch (ParseException ex) {
        ex.printStackTrace();
    }
}
final int weekDay = cal.get(Calendar.DAY_OF_WEEK);
System.out.printf("%sday\n", weekDays[weekDay - 1]);