浅谈JavaScript 代码简洁之道(9)

Bad:

class UserSettings {
 constructor(user) {
 this.user = user;
 }

 changeSettings(settings) {
 if (this.verifyCredentials()) {
  // ...
 }
 }

 verifyCredentials() {
 // ...
 }
}

Good:

class UserAuth {
 constructor(user) {
 this.user = user;
 }
 verifyCredentials() {
 // ...
 }
}

class UserSetting {
 constructor(user) {
 this.user = user;
 this.auth = new UserAuth(this.user);
 }
 changeSettings(settings) {
 if (this.auth.verifyCredentials()) {
  // ...
 }
 }
}
}

开闭原则

“开”指的就是类、模块、函数都应该具有可扩展性,“闭”指的是它们不应该被修改。也就是说你可以新增功能但不能去修改源码。

Bad:

class AjaxAdapter extends Adapter {
 constructor() {
 super();
 this.name = 'ajaxAdapter';
 }
}

class NodeAdapter extends Adapter {
 constructor() {
 super();
 this.name = 'nodeAdapter';
 }
}

class HttpRequester {
 constructor(adapter) {
 this.adapter = adapter;
 }

 fetch(url) {
 if (this.adapter.name === 'ajaxAdapter') {
  return makeAjaxCall(url).then((response) => {
  // 传递 response 并 return
  });
 } else if (this.adapter.name === 'httpNodeAdapter') {
  return makeHttpCall(url).then((response) => {
  // 传递 response 并 return
  });
 }
 }
}

function makeAjaxCall(url) {
 // 处理 request 并 return promise
}

function makeHttpCall(url) {
 // 处理 request 并 return promise
}

Good:

class AjaxAdapter extends Adapter {
 constructor() {
 super();
 this.name = 'ajaxAdapter';
 }

 request(url) {
 // 处理 request 并 return promise
 }
}

class NodeAdapter extends Adapter {
 constructor() {
 super();
 this.name = 'nodeAdapter';
 }

 request(url) {
 // 处理 request 并 return promise
 }
}

class HttpRequester {
 constructor(adapter) {
 this.adapter = adapter;
 }

 fetch(url) {
 return this.adapter.request(url).then((response) => {
  // 传递 response 并 return
 });
 }
}

里氏替换原则

名字很唬人,其实道理很简单,就是子类不要去重写父类的方法。

Bad:

// 长方形
class Rectangle {
 constructor() {
 this.width = 0;
 this.height = 0;
 }

 setColor(color) {
 // ...
 }

 render(area) {
 // ...
 }

 setWidth(width) {
 this.width = width;
 }

 setHeight(height) {
 this.height = height;
 }

 getArea() {
 return this.width * this.height;
 }
}

// 正方形
class Square extends Rectangle {
 setWidth(width) {
 this.width = width;
 this.height = width;
 }

 setHeight(height) {
 this.width = height;
 this.height = height;
 }
}

function renderLargeRectangles(rectangles) {
 rectangles.forEach((rectangle) => {
 rectangle.setWidth(4);
 rectangle.setHeight(5);
 const area = rectangle.getArea(); 
 rectangle.render(area);
 });
}

const rectangles = [new Rectangle(), new Rectangle(), new Square()];
renderLargeRectangles(rectangles);
      

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/90.html