Java敏捷开发技巧之消除代码异味

发表于:2011-9-28 09:33

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:yongbing    来源:51Testing软件测试网采编

  用一个对象代替一种类别(注意,之前是一个类代替一种类别)。

  根据之前讲的解决方法,要去掉类别代码,我们只需要为每种类别创建一个子类,比如:

abstract class UserAccount {
String id;  
String name;
String password;
Date dateOfLastPasswdChange;
abstract int getPasswordMaxAgeInDays(); 
abstract boolean canPrintReport();  
}  
class NormalUserAccount extends UserAccount {  
int getPasswordMaxAgeInDays() { 
return 90;  
}
boolean canPrintReport() {  
return true;
}
}  
class AdminUserAccount extends UserAccount {
int getPasswordMaxAgeInDays() { 
return 30;  
}
boolean canPrintReport() {  
return true;
}
}  
class GuestUserAccount extends UserAccount {
int getPasswordMaxAgeInDays() { 
return Integer.MAX_VALUE;
}
boolean canPrintReport() {  
return false;
}
}

  但问题是,三种子类的行为(里面的代码)都差不多一样,getPasswordMaxAgeInDays这个方法就一个数值不同(30,90或者Integer.MAX_VALUE)。canPrintReport这个方法也不同在一个数值(true或false)。这三种用户类型只需要用三个对象代替就行了,无须特别地新建三个子类了:

class UserAccount {
UserType userType;
String id; 
String name;
String password;
Date dateOfLastPasswdChange;
UserType getType() {
return userType;
}  

class UserType {
int passwordMaxAgeInDays;
boolean allowedToPrintReport;
UserType(int passwordMaxAgeInDays, boolean allowedToPrintReport) {
this.passwordMaxAgeInDays = passwordMaxAgeInDays;
this.allowedToPrintReport = allowedToPrintReport;
}  
int getPasswordMaxAgeInDays() {
return passwordMaxAgeInDays;
}  
boolean canPrintReport() {
return allowedToPrintReport;
}  
static UserType normalUserType = new UserType(90, true);
static UserType adminUserType = new UserType(30, true);
static UserType guestUserType = new UserType(Integer.MAX_VALUE, false);

class InventoryApp {
void login(UserAccount userLoggingIn, String password) {
if (userLoggingIn.checkPassword(password)) {
GregorianCalendar today = new GregorianCalendar();
GregorianCalendar expiryDate = getAccountExpiryDate(userLoggingIn);
if (today.after(expiryDate)) {
//提示用户修改密码
...
}  
}  
}  
GregorianCalendar getAccountExpiryDate(UserAccount account) {
int passwordMaxAgeInDays = getPasswordMaxAgeInDays(account);
GregorianCalendar expiryDate = new GregorianCalendar();
expiryDate.setTime(account.dateOfLastPasswdChange);
expiryDate.add(Calendar.DAY_OF_MONTH, passwordMaxAgeInDays);
return expiryDate;
}  
int getPasswordMaxAgeInDays(UserAccount account) {
return account.getType().getPasswordMaxAgeInDays();
}  
void printReport(UserAccount currentUser) {
boolean canPrint;
canPrint = currentUser.getType().canPrintReport();
if (!canPrint) {
throw new SecurityException("You have no right");
}  
//打印报表.
}  
}

65/6<123456>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号