TITLE: Can friends be "good"? PROBLEM: gokulj@cc.usu.edu Hi, My friend and myself have been having a big argument about this question of whether 'friend' functions are like 'goto' to in OOPS (C++). In the sense that the friend functions are against the concepts of OOP. RESPONSE: rmartin@rcmcon.com (Robert Martin), 25 Apr 94 Many people feel that friends are "ugly" because they break the encapsulation of classes. Such uses are unfortunate. A better use for friendship is to *enhance* the encapsulation of a group of collaborating classes. Sometimes classes form clusters which collaborate at in intimate level. The intimacy may be due to efficiency concerns; or it may be due to access restrictions. For example, A Driver should be able to drive a Car, but only a Mechanic should be able to tune a Carburetor. Thus the Carburetor of the Car should be hidden from the Driver, but exposed to the Mechanic. class Car { public: virtual void Drive(Driver&) = 0; private: Carburetor& GetCarburetor() {return itsCarburetor;} Carburetor itsCarburetor; friend class Mechanic; }; class Mechanic { public: void Tune(Car& theCar) { Carburetor& carb = theCar.GetCarburetor(); carb.Tune(); } }; The above shows how friendship can be used to restrict the knowledge of the Carburetor to a priviledged few. The Driver has no access to the Carburetor, and thus cannot illicitly manipulate it. Only the Mechanic can access the Carburetor within the Car. Thus, the Car and Mechanic have become part of a single larger abstraction, and the encapsulation barrier that surrounds them is kept intact by the use of friendship. Without friendship, the Carburetor would have had to be exposed in the public interface of Car, and the encapsulation would have been altogether lost. [ ... in a later response ... ] OOP is not a religion or a set of dogmas. There are some good engineering principles that have come out of OO and are valuable to software engineers. However, all things OOP are not necessarily "good". Nor is OOP the universal answer to the problem of software engineering. A designer should not ask "is this the OOP way?" Instead he should ask: "Does this make sense to do?". To help answer that the designer should be armed with the knowledge of many design principles, not just those related to OOP. There are good concepts in the object oriented paradigm. It is worthy of study, and its principles can be applied profitably. But such success does not invalidate the success of structured programming, or information modeling or any of the other advances that have been made over the last 40 years. Learn them all, weigh them all, apply them all.