高质量软件开发人员的五大习惯
作者:网络转载 发布时间:[ 2013/6/5 10:27:20 ] 推荐标签:
在这个实现里,行为方法getPostLogonMessage()没有包含任何的行为逻辑,而是简单的返回实例变量this.postLogonMessage。这个实现存在着三个问题。首先,这个实现使得我们很难理解“post logon message”的逻辑是怎么工作的,因为它被包含在一个执行两个任务的方法里。第二,getPostLogonMessage()的重用是受限制的,因为它永远和loadAccountStatus()相关联。后,在出现系统问题的情况下,CustomerAccountsSystemOutageException将会被抛出,使得方法在设置this.postLogonMessage的值之前停止了。这个实现也对测试产生了一个负面的影响,因为测试getPostLogonMessage()逻辑的方法是创建一个CustomerAccount对象,这个对象有一个在数据库里有用户名和密码的用户,而且这个用户的accountStatus被设置为“E”,被用来停止。这将导致为了这个测试必须给数据库做一个远程调用。这使得这个测试运行起来速度慢,而且由于数据库发生的改变将导致测试意想不到的失败。这个测试需要对数据库做一个远程调用,因为loadAccountStatus()方法也包含了行为逻辑,如果行为逻辑被模仿,那么测试测试的是模拟对象的行为,而不是实际对象的行为。
习惯5:行为方法能够在任何条件下被调用
第五个习惯是确保每一个行为方法提供的功能相对于其他的行为方法来说是独立的。换句话说,一个对象的行为方法能够被重复和以任何顺利调用。这个习惯使得对象传递固定的行为。例如,CustomerAccount对象的isActiveForPurchasing()和getPostLogonMessage()行为方法在它们的逻辑里都使用accountStatus的值。每一个方法对于其他的方法来说是功能独立的。例如,一个场景要求isActiveForPurchasing()被调用,接着调用getPostLogonMessage():
ICustomerAccount ca = new CustomerAccount(username, password);
ca.loadAccountStatus();
if(ca.isActiveForPurchasing()){
//go to "begin purchasing" display
...
//show post logon message.
ca.getPostLogonMessage();
} else {
//go to "activate account" display
...
//show post logon message.
ca.getPostLogonMessage();
}
另一个场景要求调用getPostLogonMessage(),而不要求调用isActiveForPurchasing():
ICustomerAccount ca = new CustomerAccount(username, password);
ca.loadAccountStatus();
//go to "welcome back" display
...
//show post logon message.
ca.getPostLogonMessage();
如果getPostLogonMessage()要求isActiveForPurchasing()首先被调用的话,CustomerAccount对象将不支持第二个场景。例如,创建两个方法来使用一个postLogonMessage实例变量,这样,它的值能够在支持场景一的方法中间得到维护,但是在支持场景二的方法中却不能:
public boolean isActiveForPurchasing() {
boolean returnValue = false;
if("A".equals(this.accountStatus)){
this.postLogonMessage = "Your purchasing account is active.";
returnValue = true;
} else if("E".equals(this.accountStatus)) {
this.postLogonMessage = "Your purchasing account has " +
"expired due to a lack of activity.";
returnValue = false;
} else {
this.postLogonMessage = "Your purchasing account cannot be " +
"found, please call customer service "+
"for assistance.";
returnValue = false;
}
return returnValue;
}
public String getPostLogonMessage() {
return this.postLogonMessage;
}

sales@spasvo.com