I have 2 constructors for my Date class. The first one just have 3 int parameter represent month, day and year. And the second one, I provide it in case user give string as one parameter to represent month/day/year.
Since software rule #1: Don't repeat code. I decide to parse the String in second constructor, and use the first constructor to verify whether the date is valid or not. So in the end I call this to provide the same 3 int parameter as the first constructor.
Well, compiler gives me this Error: error: call to this must be first statement in constructor.
I understand that I can have the second constructor this way, but this against software rule #1.
public Date(String s) {
String[] strSplit = s.split("/");
month = Integer.parseInt(strSplit[0]);
day = Integer.parseInt(strSplit[1]);
year = Integer.parseInt(strSplit[2]);
if (isValidDate(month, day, year)) {
this.month = month;
this.day = day;
this.year = year;
} else {
System.out.println("Fatal error: Invalid data.");
System.exit(0);
}
}
Please take a look the 1st and 2nd constructor:
class Date {
private int month;
private int day;
private int year;
public Date(int month, int day, int year) {
if (isValidDate(month, day, year)) {
this.month = month;
this.day = day;
this.year = year;
} else {
System.out.println("Fatal error: Invalid data.");
System.exit(0);
}
}
public Date(String s) {
String[] strSplit = s.split("/");
int m = Integer.parseInt(strSplit[0]);
int d = Integer.parseInt(strSplit[1]);
int y = Integer.parseInt(strSplit[2]);
this(m, d, y);
}
.
.
.
public static void main(String[] argv) {
Date d1 = new Date(1, 1, 1);
System.out.println("Date should be 1/1/1: " + d1);
d1 = new Date("2/4/2");
System.out.println("Date should be 2/4/2: " + d1);
}
}