【发布时间】:2018-11-09 06:23:44
【问题描述】:
我目前正在学习 Java。我有一个带有超类(IndexCard)的项目,有两个子类(EmployeeIndexCard 和 CustomerIndexCard)。这两个子类非常相似,但它们的实例变量不同,因此构造函数也不同。
他们在这里:
class EmployeeIndexCard extends IndexCard {
public WorkArea workArea ;
protected String password;
public employeeIndexCard(String name, String password, String adress, String phone, String email, String workArea) {
super(name, adress, phone, email);
this.password = password;
this.workArea = WorkArea.valueOf(workArea);
}
}
class CustomerIndexCard extends IndexCard {
public customerIndexCard(String name, String adress, String phone, String email) {
super(name, adress, phone, email);
}
}
我想知道我做错了什么,因为为了创建这些类的实例,我创建了两个非常相似的方法:
/**
* Create an instance of EmployeeIndexCard.
*/
public static void employeeIndexCard(String name, String dni, String password, String adress, String phone, String email, String workArea) {
if (Utils.validateDni(dni) && !IndexCard.list.containsKey(dni)) {
IndexCard.list.put(dni, new EmployeeIndexCard(name, password, adress, phone, email, workArea));
} else {
throw new InvalidParameterException();
}
}
/**
* Create an instance of CustomerIndexCard.
*/
public static void customerIndexCard(String name, String dni, String adress, String phone, String email) {
if (Utils.validateDni(dni) && !IndexCard.list.containsKey(dni)) {
IndexCard.list.put(dni, new FichaCliente(name, adress, phone, email));
} else {
throw new InvalidParameterException();
}
}
有没有什么办法可以重构代码来合并最后两个几乎相同的方法?
【问题讨论】:
-
对于初学者,请不要为方法提供带有大写字母的类名。这只会造成混乱。
-
为什么还需要这些方法?只需将验证移至构造函数即可。
-
@Kayaman 如果我将验证移到构造函数中,它不会仍然是重复代码吗?
-
您可以将公共部分放在超类构造函数中。现在,您可以使用构造函数(它们没有得到验证)或使用您创建的那些方法来创建对象。
标签: java methods refactoring subclass