一句话:通过分析 7 个开源项目,实证揭示 C++ 开发者使用 const 表达不可变性的现状与漏标差距。
尽管语言设计中的最佳实践建议尽可能使用不可变性,但开发者实际采纳程度缺乏实证证据。本文研究 C++ 开发者如何使用 const 限定符来表达不可变类与方法。作者分析 7 个中大型开源项目,收集两类数据:开发者书写的 const 标注,以及一个简单静态分析所识别出的明显可加 const 的方法。结果显示,非平凡类(方法数超过 3)中位数仅约 5% 为不可变;但方法层面的不可变性标注相当普遍:开发者对 46% 的方法加了 const,静态分析估计至少 51% 的方法可以加 const,且在未标注方法中至少 6% 被漏标。文章进一步讨论了 const 的实际使用模式与这些发现的含义。
Best practices for developers, as encoded in recent programming language designs, recommend the use of immutability whenever practical. However, there is a lack of empirical evidence about the uptake of this advice. Our goal is to understand the usage of immutability by C++ developers in practice. This work investigates how C++ developers use immutability by analyzing their use of the C++ immutability qualifier, const, and by analyzing the code itself. We answer the following broad questions about const usage: 1) do developers actually write non-trivial (more than 3 methods) immutable classes and immutable methods? 2) do developers label their immutable classes and methods? We analyzed 7 medium-to-large open source projects and collected two sources of empirical data: 1) const annotations by developers, indicating an intent to write immutable code; and 2) the results of a simple static analysis which identified easily const-able methods---those that clearly did not mutate state. We estimate that 5% of non-trivial classes (median) are immutable. We found the vast majority of classes do carry immutability labels on methods: surprisingly, developers const-annotate 46% of methods, and we estimate that at least 51% of methods could be const-annotated. Furthermore, developers missed immutability labels on at least 6% of unannotated methods. We provide an in-depth discussion on how developers use const and the results of our analyses.