我有代码并正在考虑使其更加纯粹和干净。
我觉得去掉方法中的多重返回会很好。
怎么可能重构呢? 也许我应该使用一些模式? 请指教。提前致谢。
class Test{
private client;
private concreteMixer;
constructor(client, concreteMixer){
this.client = client;
this.concreteMixer = concreteMixer;
}
public method(){
let form = new Form();
if(form.isSubmitted()){
if(form.isValid()){
let field = form.getField();
let infoField = this.client.testField(field);
if(!infoField){
form.setError('This is not valid field');
return form;
}
let coffee = this.concreteMixer.makeСoffee();
//two days have passed
if(!coffee){
form.setError('I want coffee');
return form;
}
this.concreteMixer.pourInThermosBottle();
//two days have passed
return coffee;
}
}
return form;
}
}
最佳答案
我会这么做
/**
* Comment
*/
class Test {
/**
* Comment
*/
protected client;
/**
* Comment
*/
protected concreteMixer;
/**
* Comment
*/
constructor(client, concreteMixer) {
this.client = client;
this.concreteMixer = concreteMixer;
}
/**
* Comment
*/
public method() {
const form = new Form();
// Comment
if (!form.isSubmitted() || !form.isValid()) {
return form;
}
// Comment
const field = form.getField();
// Comment
const infoField = this.client.testField(field);
// Comment
if (!infoField) {
form.setError(ERROR_CODE_01);
return form;
}
// Comment
const coffee = this.concreteMixer.makeСoffee();
//two days have passed
if (!coffee) {
form.setError(ERROR_CODE_02);
return form;
}
// Comment
this.concreteMixer.pourInThermosBottle();
// two days have passed
return coffee;
}
}
<小时/>
我用 const
替换了 let
事件。当你的变量不改变时使用const。当它使用 let
时。
当您遇到以下情况时:
if (something) {
... a lot of lines
}
// end of function
您可以使用:
if (!something) {
return;
}
因此,您赢得了很多行的缩进级别。
<小时/>使用错误代码而不是直接的错误字符串。因此您的应用程序的用户可以以编程方式处理它。
<小时/>注释您的代码以解释发生的情况。因此,如果其他编码员或您 future 的自己发现了这段代码,它会更容易理解。至少:类做什么? 方法
做什么?
我将 private
替换为 protected
,因此如果有一天您想从您的类继承,您无需进一步更改即可实现。
关于javascript - 我如何重构我的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47458120/