高质量软件开发人员的五大习惯
作者:网络转载 发布时间:[ 2013/6/5 10:27:20 ] 推荐标签:
构造器被用来产生对象的实例。构造器的名字永远和对象的名字相同(译者:这里的“对象”应该是“类”的意思,以下相同)。既然构造器的名字是无法改变的,它的名字不能表达出它要行使的其他功能。因而,它好履行尽量少的工作。另一方面,状态的改变和行为方法的名称使用描述性的名称来表达它们更加复杂的意图,像在“习惯2:方法名要清晰地表达方法的意图”描述的那样。下面的例子将要表明:软件的可读性很高,因为构造器仅仅产生对象的实例,而让行为和状态改变的方法去剩下的事情。
注:在例子中使用“…”表示它们在现实案例中是必须的,但是它们与例子的意图无关
String username = "robertmiller";
String password = "java.net";
ICustomerAccount ca = new CustomerAccount(username, password);
if(ca.isRequestedUsernameValid() && ca.isRequestedPasswordValid()) {
...
ca.createNewActiveAccount();
...
}
另一方面,那些构造器的功能超过载入实例变量的对象是难于理解的,并且容易被误用,因为它们的名称没有传递它们的意图。例如,下面的这个构造器额外的调用一个方法用来远程调用数据库或者Web服务,目的是为了事先载入一个账户的状态。
//Constructor that performs too much work!
public CustomerAccount(String username, String password)
throws CustomerAccountsSystemOutageException {
this.password = password;
this.username = username;
this.loadAccountStatus();//unnecessary work.
}
//Remote call to the database or web service.
public void loadAccountStatus()
throws CustomerAccountsSystemOutageException {
...
}
一个开发人员使用了这个构造器,但他没有意识到构造器已经做了一个远程调用,因而做了两个远程调用。
String username = "robertmiller";
String password = "java.net";
try {
//makes a remote call
ICustomerAccount ca = new CustomerAccount(username, password);
//makes a second remote call
ca.loadAccountStatus();
} catch (CustomerAccountsSystemOutageException e) {
...
}

sales@spasvo.com