How C++ Developers Use Immutability Declarations: an Empirical StudyTechnical TrackIndustry Program
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. In particular, 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. On average, we found that about 12% of non-trivial classes are immutable. We found the vast majority of classes do benefit from 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 write const and the results of our analyses.