2

我有一个array问题 ( interface),我需要根据问题类型将其发送到许多函数中的一个。我认为我的一系列if陈述非常丑陋,我希望有一种符合 SOLID 的方法来做到这一点。我相信我违反了 O(对扩展开放,对修改关闭)。

renderQuestionList(contents: Question[]): HTMLElement {
    return yo`
        <div>${contents.map(q => {
            if (q.type == 'passfailna') { return this.renderQuestionPassfailna(q) };
            if (q.type == 'yesno') { return this.renderQuestionYesno(q) };
            if (q.type == 'numeric') { return this.renderQustionNumeric(q) };
        })}
        </div>`;
}

然后,

    renderQuestionPassfailna(q: Question): any {
        return yo`<div>Stuff</div>`;
    }
    renderQuestionYesno(q: Question): any {
         return yo`<div>Other Stuff</div>`;
    }
    renderQustionNumeric(q: Question): any {
         return yo`<div>I'm Helping!</div>`;
    }
4

2 回答 2

2

这很丑。如何构建功能图?也许像

constructor() {
   this.questions = {
      passfailna: q => this.renderQuestionPassfailna(q),
      yesno: q => this.renderQuestionYesno(q),
      numeric: q => return this.renderQustionNumeric(q)
   };
}

renderQuestionList(contents: Question[]): HTMLElement {
    return yo`<div>${contents.map(q => this.questions[q.type](q))}</div>`;
}
于 2018-08-26T14:00:50.027 回答
1

如果模板里面的逻辑太大,那么可以移到一个函数中,比如

renderQuestionList(contents: Question[]): HTMLElement {
    return yo`
        <div>${contents.map(q => renderQuestion(q))}
        </div>`;
}

    renderQuestion(q):HTMLElement {
        if (q.type == 'passfailna') { return this.renderQuestionPassfailna(q) };
        if (q.type == 'yesno') { return this.renderQuestionYesno(q) };
        if (q.type == 'numeric') { return this.renderQustionNumeric(q) };
    }

但是,我会质疑一次生成如此大的树是否明智。当我使用 YO 时,我更喜欢生成小项目,然后使用appendChild. 例如,

renderQuestionList(contents: Question[]): HTMLElement {
    let div = yo`<div> </div>`;
    contents.forEach(q => {
         div.appendChild(renderQuestion(q));
    });
    return div;
}
于 2018-08-27T13:39:35.697 回答