破坏应用程序的最有效方法是创建GOD http://en.wikipedia.org/wiki/God_object类。这些类跟踪大量信息并承担多项职责。一项代码更改很可能会影响该类的其他部分,从而间接影响使用该代码的所有其他类。这反过来又导致了更大的维护混乱,因为除了添加新功能之外没有人敢做任何改变。
以下示例是一个 TypeScript 类,它定义了Person
,此类不应包含电子邮件验证,因为这与个人行为无关:
class Person {
public name : string;
public surname : string;
public email : string;
constructor(name : string, surname : string, email : string){
this.surname = surname;
this.name = name;
if(this.validateEmail(email)) {
this.email = email;
}
else {
throw new Error("Invalid email!");
}
}
validateEmail(email : string) {
var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
return re.test(email);
}
greet() {
alert("Hi!");
}
}
我们可以通过从 Person 类中删除电子邮件验证的责任并创建一个新的来改进上面的类Email
将承担该责任的类:
class Email {
public email : string;
constructor(email : string){
if(this.validateEmail(email)) {
this.email = email;
}
else {
throw new Error("Invalid email!");
}
}
validateEmail(email : string) {
var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
return re.test(email);
}
}
class Person {
public name : string;
public surname : string;
public email : Email;
constructor(name : string, surname : string, email : Email){
this.email = email;
this.name = name;
this.surname = surname;
}
greet() {
alert("Hi!");
}
}
确保一个类具有单一职责,使其在默认情况下也更容易看到它的作用以及如何扩展/改进它。