AI Agent初体验:使用感受与评测
AI编程实践中,因缺乏规范导致代码混乱:分组件编写困难,防御性代码过多,变量名简略如使用单字母,且过度设计。这些问题需从架构师视角提前约定规范,避免无效代码堆积。
好一阵子没更新了,这段时间实习忙得够呛,一直没顾上写点东西。说实话,面对AI这波浪潮,知道不少,但实践确实没跟上。Agent的使用还停留在对话加skill这种初级阶段,Harness之类的东西虽然听说过,网上也学了不少技巧,但一直没落地去试。所以这篇文章谈不上什么深度,更多的是一些实际踩坑后的碎碎念。好了,言归正传,聊聊在AI编程中遇到的那些问题。
背景
这次实习参与了个新项目开发,算是老项目里独立出来的一个工具。AI带来的感受是——拿到需求文档和接口文档后,框框就开始写代码,但写出来的代码相当混乱,即便给了HTML原型图,也很难一步到位把设计稿还原出来。至于分组件的编写,更是需要人工干预才行。所以,如果前期没有约定好规范,后面的代码就是一座屎山,出了bug也只不过是在屎山上拉屎。这几天虽然没什么正事儿,但一直在做CR、重构逻辑,确实累得够呛。(文中示例代码均做过处理或为废稿,不存在泄露问题)
主要问题
1. 不太喜欢分组件编写
2. 防御性代码过多
例一:请求字段兜底过多
function parseImageItem(im: Record): ImageItem | null {
const imageUrl = String(im.imageUrl im.image_url im.url im.imgUrl '').trim()
if (!imageUrl) return null
const imgSrcRaw = im.imageSource im.image_source im.imgSource im.img_source
const itemStageRaw = im.itemStageAction im.item_stage_action im.subStageAction im.sub_stage_action im.bizStage
return {
historyId: im.historyId != null String(im.historyId) : im.history_id != null String(im.history_id) : undefined,
imageUrl,
imageName: String(im.imageName im.image_name im.name '图片').trim() || '图片',
sourceType: String(im.sourceType im.source_type ''),
sourceId: String(im.sourceId im.source_id ''),
imageId: im.imageId != null String(im.imageId) : im.image_id != null String(im.image_id) : undefined,
imageSource: imgSrcRaw != null && String(imgSrcRaw).trim() String(imgSrcRaw).trim() : undefined,
itemStageAction: itemStageRaw != null && String(itemStageRaw).trim() String(itemStageRaw).trim() : undefined,
historyStage: toNumber(im)
}
}
例二:屎上拉屎
const currentRuquest = new Map>
/** 并发合并:已有在途请求则直接返回其 Promise,避免重复 HTTP */
function dedupeConcurrentSlotsRead(taskId: string, execute: () => Promise): Promise {
const existing = currentRuquest.get(taskId) as Promise | undefined
if (existing) return existing
const pending = execute().finally(() => {
if (currentRuquest.get(taskId) === pending) currentRuquest.delete(taskId)
})
currentRuquest.set(taskId, pending)
return pending
}
3. 不喜欢用外部库
4. 变量名简略
这不知道是不是提示词的问题——要求用最少最简洁的代码解决问题,结果AI直接甩出 const a 这种变量名,代码review的时候根本没法一眼看明白。举个例子:
const did = props.dialogId.trim()
if (!did || typeof sessionStorage === 'undefined') {
clear()
return
}
try {
const raw = sessionStorage.getItem(ExportSessionKey(did))
if (!raw) {
clear()
return
}
const o = JSON.parse(raw) as { ids?: unknown[]; urls?: unknown[] }
ExportImageIds.value = new Set((o.ids || []).map((x) => String(x).trim()).filter(Boolean))
extraExportImageUrls.value = new Set((o.urls || []).map((x) => String(x).trim()).filter(Boolean))
} catch {
clear()
}
总之,很难受。
5. 过度设计
这个老生常谈了,就不多说了。
总结
暂时先写这么多。还有数据结构设计等问题,同样让人感觉无效代码过多。以上问题,说到底都是项目一开始没设计好规范导致的。现在其实有很多skill和工程手段可以约束,比如前段时间的 claude.md,里面就做了不少不错的约束。这方面倒是值得仔细研究一下Claude的源码,设计模式确实有意思。有时间专门研究一下,再出篇文章细聊。归根结底,磨刀不误砍柴工,要从架构师的视角去完成需求,而不是当个普通程序员。
好了,要去优化屎山了,祝好。
