Before
public class Triangle {
Point p1, p2, p3;
Triangle(Point p1, Point p2, Point p3) {
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
}
void someMethod() {
// do something with the Points p1,p2,p3
}
}
After (Version 1)
public class Triangle {
Point p1, p2, p3;
String colorName = ""; // default is empty colorName
Triangle(Point p1, Point p2, Point p3) { // unchanged
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
// colorName stays empty (declaration)
}
Triangle(Point p1, Point p2, Point p3, String colorName) {
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
this.colorName = colorName;
}
void someMethod() {
if (colorName.equals("")) {
// do something with the Points p1,p2,p3
} else {
// do something with the Points and colorName
}
}
}
After (Version 2, My Preference)
public class Triangle {
Point p1, p2, p3;
String colorName; // no default here
Triangle(Point p1, Point p2, Point p3) {
this(p1, p2, p3, ""); // default is empty colorName
}
Triangle(Point p1, Point p2, Point p3, String colorName) {
this.p1 = p1; // same as After (version 1)
this.p2 = p2;
this.p3 = p3;
this.colorName = colorName;
}
void someMethod() { // same as After (version 1)
if (colorName.equals("")) {
// do something with the Points p1,p2,p3
} else {
// do something with the Points and colorName
}
}
}
allan gottlieb