好的代码可读性很高,就像在读英文句子一样,顺着读下来很清晰、很流畅。
下面是 TypeScript 源码 src\server\editorServices.ts 里的一段,大家可以感受一下:
/** @internal */
forEachEnabledProject(cb: (project: Project) => void) {
this.forEachProject(project => {
if (!project.isOrphan() && project.languageServiceEnabled) {
cb(project);
}
});
}
getDefaultProjectForFile(fileName: NormalizedPath, ensureProject: boolean): Project | undefined {
return ensureProject ? this.ensureDefaultProjectForFile(fileName) : this.tryGetDefaultProjectForFile(fileName);
}
/** @internal */
tryGetDefaultProjectForFile(fileNameOrScriptInfo: NormalizedPath | ScriptInfo): Project | undefined {
const scriptInfo = isString(fileNameOrScriptInfo) ? this.getScriptInfoForNormalizedPath(fileNameOrScriptInfo) : fileNameOrScriptInfo;
return scriptInfo && !scriptInfo.isOrphan() ? scriptInfo.getDefaultProject() : undefined;
}
/** @internal */
ensureDefaultProjectForFile(fileNameOrScriptInfo: NormalizedPath | ScriptInfo): Project {
return this.tryGetDefaultProjectForFile(fileNameOrScriptInfo) || this.doEnsureDefaultProjectForFile(fileNameOrScriptInfo);
}
private doEnsureDefaultProjectForFile(fileNameOrScriptInfo: NormalizedPath | ScriptInfo): Project {
this.ensureProjectStructuresUptoDate();
const scriptInfo = isString(fileNameOrScriptInfo) ? this.getScriptInfoForNormalizedPath(fileNameOrScriptInfo) : fileNameOrScriptInfo;
return scriptInfo ?
scriptInfo.getDefaultProject() :
(this.logErrorForScriptInfoNotFound(isString(fileNameOrScriptInfo) ? fileNameOrScriptInfo : fileNameOrScriptInfo.fileName), Errors.ThrowNoProject());
}
提高可读性的关键在于命名和逻辑拆分,当你不能为一段逻辑准确命名的时候,可能就说拆分的还不够细,其职责还不够明确 ,就需要再进一步的优化代码组织关系了。
欢迎关注微信公众号:文本魔术,了解更多?