I'm a beginner i have an assignment to write a Date class (as part of a bigger project). in my question i focus on the constructor. here's some background: the given guidelines are that the date is not expected to be valid and the following instance variables expect this input range: day- integer 1-31 month- integer 1-12 year- integer 4 digits year.
now, if an invalid day/month/year or invalid date (such as 31.2.2010) is entered, the object will be created with the date of 1.1.2000.
this is the code I've come up with and it does compile and seem to work fine.
public class Date
{
private int _day;
private int _month;
private int _year;
public Date (int day, int month, int year)
{
switch (month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12: if ((day>0 && day<32) && (year>999 && year<10000))
{
_day=day;
_month=month;
_year=year;
}
else
{
_day=1;
_month=1;
_year=2000;
}
break;
case 4:
case 6:
case 9:
case 11: if ((day>0 && day<31) && (year>999 && year<10000))
{
_day=day;
_month=month;
_year=year;
}
else
{
_day=1;
_month=1;
_year=2000;
}
break;
case 2: if (leap(year))
{
if ((day>0 && day<30) && (year>999 && year<10000))
{
_day=day;
_month=month;
_year=year;
}
else
{
_day=1;
_month=1;
_year=2000;
}
break;
}
else
{
if ((day>0 && day<29) && (year>999 && year<10000))
{
_day=day;
_month=month;
_year=year;
}
else
{
_day=1;
_month=1;
_year=2000;
}
break;
}
}
}
/** check if leap year */
private boolean leap (int y)
{
return (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0);
}
}
here are my questions:
- is it fine to put all that code in the constructor? will it greatly affect the processing time or cause an error? is there an alternative if its a problem?
- is any part of the code could be considered a bad practice? such as the switches and ifs? I'm not feeling to confident with this build despite it working fine...