Selective friends in C++. (10th May 2018) - Márton, Gábor; Porkoláb, Zoltán
Summary: There is a strong prejudice against the friendship access control mechanism in C++. People claim that friendship breaks the encapsulation, reflects bad design, and creates too strong coupling. However, friends appear even in the most carefully designed systems, and if it is used judiciously (like using the attorney‐client idiom), they may be better choice than widening the public interface of the class. In this paper, we investigate how the friendship mechanism is used in C++ programs. We have made measurements on several open source projects to understand the current use of friends. Our results show various holes and errors in friend usage, like friend functions accessing only public members or not accessing members at all or the class, which declare friends has no private members at all. The results also show that friend functions actually use only a low percentage of the private members they were granted to access, which is a source of errors. These results have motivated us to propose a selective friend language construct for C++, which can restrict friendship only to well‐defined members. Such a new language element may decrease the degradation of encapsulation and significantly increase the diagnostic capacity of the compiler. We have created a proof‐of‐concept implementation based on the LLVM/Clang compiler infrastructure to show that such constructs can be established with a minimal syntactical and compilation overhead.