有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java哪种实现更好(DRY和KISS)

下面是我返回月份名称的方法。在第一个实现中,我使用switch/case,这个方法更长,验证在最后一行。在第二行,我在第一行进行了验证,并用months名称声明了表,而不是switch/case

当我想到亲吻和干燥的原则时,哪一个更好

public String getMonthName(int month) {
    switch (month) {
        case 1:
            return "January";
        case 2:
            return "February";
        case 3:
            return "March";
        case 4:
            return "April";
        case 5:
            return "May";
        case 6:
            return "June";
        case 7:
            return "July";
        case 8:
            return "August";
        case 9:
            return "September";
        case 10:
            return "October";
        case 11:
            return "November";
        case 12:
            return "December";
        default:
            throw new IllegalArgumentException("month must be in range 1 to 12");
    }
}

或者这个

public String getMonthNameNew(int month) {
    if ((month < 1) || (month > 12)) throw new IllegalArgumentException("month must be in range 1 to 12");
    String[] months = {
            "January",
            "February",
            "March",
            "April",
            "May",
            "June",
            "July",
            "August",
            "September",
            "October",
            "November",
            "December"
    };
    return months[month - 1];
}

共 (0) 个答案