Detect months with 31 days

前端 未结 19 1624
南旧
南旧 2020-12-18 01:53

Is there an analogous form of the following code:

if(month == 4,6,9,11)
{
  do something;
}

Or must it be:

if(month == 4 ||         


        
19条回答
  •  不思量自难忘°
    2020-12-18 02:41

    I think your code will be more self-documenting if you use the static constants built into Calendar (e.g., Calendar.JANUARY, etc.)

    If you do this often - more than once - I'd recommend writing a method named has31Days() or isReportMonth() to do the check in one place.

    UPDATE:

    The important thing isn't the months that have 31 days - it's the business rule that tells you something about reports for those months.

    I might write it like this (hope I got the months with 31 days right):

    public class ReportEngine
    {
        public boolean isReportRequired(int month)
        {
            if ((month < Calendar.JANUARY) || (month > Calendar.DECEMBER))
                throw new IllegalArgumentException("Invalid month: " + month);
    
            // Reports are required for months with 31 days.
            return ((month == Calendar.JANUARY) || 
                    (month == Calendar.MARCH) || 
                    (month == Calendar.MAY) ||
                    (month == Calendar.JULY) || 
                    (month == Calendar.AUGUST) || 
                    (month == Calendar.OCTOBER) ||
                    (month == Calendar.DECEMBER));
        }
    }
    

提交回复
热议问题