分析代码以改进,包括代码异味、设计模式和最佳实践。当用户请求代码分析、代码审查或建议时调用。
代码嗅觉分析器是一项面向实际任务的技能,主要用于分析代码文件,以便进行可能的改进,包括代码嗅觉、设计模式和最佳做法;提供增强可读性、可维护性的建议。
从功能定位来看,该技能强调把分散的操作要求整理成清晰、可复用的处理流程,使用户能够围绕既定目标快速准备输入、选择执行方式并获得结构化结果。实际使用前应先确认任务范围、数据来源、运行环境、必要权限和关键参数,再依据技能说明逐步执行;
若输入条件不完整,应先补齐信息或采用保守配置,避免因错误假设导致结果偏离需求。执行过程中需要关注工具调用是否成功、接口或依赖是否可用、输出格式是否符合预期,并对异常提示、缺失字段和边界情况进行处理;涉及批量任务时,还应保存进度,避免中断后重复操作。
对代码文件进行分析,识别潜在的改进点,包括代码异味(Code Smells)、设计模式应用机会以及最佳实践遵循情况。在不改变功能的前提下,提供提升可读性、可维护性和性能的具体建议。
在以下情况下调用该能力:
识别以下常见代码异味:
推荐适用于当前代码结构的设计模式:
检查是否符合语言特定的最佳实践:
评估代码表达的清晰程度:
评估代码后续修改与扩展的难易程度:
识别潜在的性能优化机会:
每条建议均需包含以下要素:
对问题或改进机会的清晰说明。
// 展示存在问题的代码
// 展示改进后的代码
解释该变更为何有益。
优先级:高
当前代码:
function processOrder(order) {
// Validate order
if (!order.items || order.items.length === 0) {
throw new Error('Order has no items');
}
if (!order.customer) {
throw new Error('Customer is required');
}
// Calculate totals
let subtotal = 0;
for (const item of order.items) {
subtotal += item.price * item.quantity;
}
const tax = subtotal * 0.1;
const total = subtotal + tax;
// Apply discount
if (order.discountCode) {
total = total * 0.9;
}
// Save to database
db.orders.insert({
...order,
subtotal,
tax,
total,
createdAt: new Date(),
});
// Send confirmation email
emailService.send(order.customer.email, 'Order Confirmed', total);
return {orderId: order.id, total};
}
建议改进:
function processOrder(order) {
validateOrder(order);
const pricing = calculatePricing(order);
saveOrder(order, pricing);
sendConfirmation(order, pricing.total);
return {orderId: order.id, total: pricing.total};
}
function validateOrder(order) {
if (!order.items?.length) throw new Error('Order has no items');
if (!order.customer) throw new Error('Customer is required');
}
function calculatePricing(order) {
const subtotal = order.items.reduce((sum, item) => sum + item.price * item.quantity, 0);
const tax = subtotal * 0.1;
let total = subtotal + tax;
if (order.discountCode) {
total *= 0.9;
}
return {subtotal, tax, total};
}
function saveOrder(order, pricing) {
db.orders.insert({
...order,
...pricing,
createdAt: new Date(),
});
}
function sendConfirmation(order, total) {
emailService.send(order.customer.email, 'Order Confirmed', total);
}
依据说明:
const/let 替代 var?.)和空值合并操作符(??)any 类型with 语句)Optional 替代 null 值判断wx:key相关专题
热门下载
相关下载
精品课程
共6课时 | 54.7万人学习
共89课时 | 133.9万人学习
共49课时 | 82.5万人学习