[论文解读] How Propense Are Large Language Models at Producing Code Smells? A Benchmarking Study
本文提出了 CodeSmellEval,一个基准测试,通过一种新指标——倾向性异味分数(PSC),衡量大型语言模型(LLMs)生成代码异味的倾向性,该指标分析模型的 logits。研究发现,CodeLlama 和 Mistral 频繁生成如 consider-merging-isinstance 和 chained-comparison 等异味,揭示了在代码质量方面存在超越准确性的关键差距。
Large Language Models (LLMs) have shown significant potential in automating software engineering tasks, particularly in code generation. However, current evaluation benchmarks, which primarily focus on accuracy, fall short in assessing the quality of the code generated by these models, specifically their tendency to produce code smells. To address this limitation, we introduce CodeSmellEval, a benchmark designed to evaluate the propensity of LLMs for generating code smells. Our benchmark includes a novel metric: Propensity Smelly Score (PSC), and a curated dataset of method-level code smells: CodeSmellData. To demonstrate the use of CodeSmellEval, we conducted a case study with two state-of-the-art LLMs, CodeLlama and Mistral. The results reveal that both models tend to generate code smells, such as simplifiable-condition and consider-merging-isinstance. These findings highlight the effectiveness of our benchmark in evaluating LLMs, providing valuable insights into their reliability and their propensity to introduce code smells in code generation tasks.
研究动机与目标
- 为解决缺乏评估代码质量(超越准确性)的指标问题,特别是 LLM 在代码生成过程中引入代码异味的倾向性。
- 开发一种与模型无关的基准测试,以系统性评估 LLM 生成方法级代码异味的倾向性。
- 提供一个新的数据集 CodeSmellData,包含从 GitHub 收集的 142,000 个经筛选的 Python 方法级代码异味,以支持严格的基准测试。
- 通过针对两种最先进的 LLM(CodeLlama 和 Mistral)的案例研究,展示该基准测试的实用性,揭示其生成异味的倾向性。
- 通过识别当前模型最可能引入的代码异味,提升基于 LLM 的代码生成的可解释性与可靠性。
提出的方法
- 提出倾向性异味分数(PSC)指标,通过计算最终 Transformer 层 logits 中与特定代码异味相关联的 token 的平均对数概率,来衡量生成倾向。
- 设计一种协议,利用静态分析(Pylint)和自定义对齐函数,从模型生成的 token 中提取并匹配已知的代码异味类型。
- 构建 CodeSmellData 数据集,包含从公开 GitHub 仓库中提取的 142,000 个唯一的方法级代码异味,并经人工验证其类型与位置。
- 使用自举抽样(每样本 100 个实例)估计 PSC 分布并评估统计显著性,以 0.5 为误差检测阈值。
- 通过从提示词生成代码并计算每种代码异味类型的 PSC,将基准测试应用于两种 LLM —— CodeLlama-7b-Instruct-hf 和 Mistral-7B-v0.3。
- 通过可视化和比较不同模型与异味类型之间的 PSC 分布,识别高倾向性异味,并利用统计差异推断模型行为。

实验结果
研究问题
- RQ1LLM 在代码生成过程中生成特定类型代码异味的倾向性如何?
- RQ2当前 LLM 最常生成哪些代码异味类型?不同模型之间的 PSC 得分有何差异?
- RQ3PSC 指标如何区分高倾向性与低倾向性代码异味?它为理解模型行为提供了哪些洞见?
- RQ4LLM 在基于公开代码库进行训练时,多大程度上继承并重现了训练数据中存在的代码异味?
- RQ5PSC 指标能否作为衡量代码质量的可靠、可解释且与模型无关的指标,超越标准生成指标?
主要发现
- CodeLlama 和 Mistral 均表现出高倾向性生成代码异味,特别是 R1701(consider-merging-isinstance)、R1716(chained-comparison)和 W0718(broad-exception-caught),其 PSC 得分显著高于 0.5 的阈值。
- consider-merging-isinstance(R1701)的 PSC 得分几乎是 disallowed-name(C0104)的两倍,表明模型对这一特定异味存在强烈倾向。
- 如 disallowed-name(C0104)、too-many-arguments(R0913)和 non-ascii-name(C2401)等异味的 PSC 得分低于阈值,表明其生成倾向较低,可能因其特异性与上下文依赖性较强。
- 该基准测试成功识别出 LLM 更倾向于生成结构性或语法性异味(如冗余条件判断、链式比较),而非语义性或命名相关异味。
- PSC 指标通过将模型 logits 与特定代码异味类型关联,展现出可解释性,提供了一种无需真实代码作为参考的黑箱方法来评估代码质量。
- 案例研究证实,基于公开代码库训练的 LLM 会继承并重现常见的代码质量问题,表明训练数据质量直接影响生成代码的质量。

阅读本论文
在 Nubint 阅读器中打开原文,边读边就任意段落提问。
在 Nubint 中阅读本论文本解读由 AI 根据论文原文生成,引用前请核对原文。