本文约束新增和修改代码时的代码质量形态。它只关注函数设计、命名、控制结构、错误处理、注释、副作用、重复和可读性,不替代前后端各自的架构开发规范。
if 包裹。Bad:
function submit(user, form, config, notify) {
if (user) {
if (form.valid) {
if (config.enabled) {
save(user, form);
notify.success();
}
}
}
}
Good:
function submit(options: SubmitOptions) {
if (!options.user) return;
if (!options.form.valid) return;
if (!options.config.enabled) return;
save(options.user, options.form);
options.notify.success();
}
is、has、can、should 开头。getUser、validateEmail、saveRole。handle 或 on 前缀,例如 handleSubmit、onDialogClose。save、update、delete、load、fetch、sync。i 除外。Bad:
const visible = user.status === "enabled";
function userData() {
return api.getUser();
}
Good:
const isVisible = user.status === "enabled";
function getUserData() {
return api.getUser();
}
if/else。switch、策略方法或枚举方法。map、filter。reduce。for / for...of。switch 或长 if/else 中堆大量业务逻辑,复杂分支必须拆成独立函数。Bad:
function getStatusLabel(status: string) {
if (status === "enabled") return "启用";
if (status === "disabled") return "禁用";
if (status === "pending") return "待处理";
if (status === "locked") return "锁定";
return "未知";
}
Good:
const statusLabels: Record<string, string> = {
enabled: "启用",
disabled: "禁用",
pending: "待处理",
locked: "锁定"
};
function getStatusLabel(status: string) {
return statusLabels[status] ?? "未知";
}
catch。catch 后必须处理、记录、转换或重新抛出异常。null、false 或空数组,除非调用方能明确区分该状态。Bad:
async function loadUser() {
try {
return await api.getUser();
} catch (error) {
console.log(error);
}
}
Good:
async function loadUser() {
try {
return await api.getUser();
} catch (error) {
showErrorMessage("用户信息加载失败");
throw error;
}
}
i++ // 增加 i。TODO。Bad:
// 遍历用户
users.forEach(user => {
// 设置名称
user.name = user.name.trim();
});
Good:
// 后端历史数据可能包含首尾空格,提交前统一清理,避免唯一性校验误判。
const normalizedUsers = users.map(user => ({
...user,
name: user.name.trim()
}));
Bad:
function normalizeUser(user: User) {
user.name = user.name.trim();
return user;
}
Good:
function normalizeUser(user: User) {
return {
...user,
name: user.name.trim()
};
}
Bad:
const userStatus = row.status === 1 ? "启用" : "禁用";
const roleStatus = role.status === 1 ? "启用" : "禁用";
const postStatus = post.status === 1 ? "启用" : "禁用";
Good:
function getEnabledStatusLabel(status: number) {
return status === 1 ? "启用" : "禁用";
}
const userStatus = getEnabledStatusLabel(row.status);
const roleStatus = getEnabledStatusLabel(role.status);
const postStatus = getEnabledStatusLabel(post.status);
Bad:
if ((user.age > 18 && user.status === 1 && !user.deleted) || user.role === "admin") {
allowAccess();
}
Good:
const isActiveAdult = user.age > 18 && user.status === 1 && !user.deleted;
const isAdmin = user.role === "admin";
if (isActiveAdult || isAdmin) {
allowAccess();
}
完成代码后必须运行与改动相关的检查。
建议静态检查覆盖:
catch