How to Remove a Friend Declaration While Preserving Design
The usage of the "friend" keyword in object-oriented design can create tight dependencies and hinder maintainability. This article provides a comprehensive approach to remove a friend declaration while preserving the overall design of the system.
Problem Background:
Consider a scenario where two classes, ClassA and ClassAAccessor, have a friend relationship. ClassA represents a shared resource with protected methods, while ClassAAccessor serves as a helper to manage access to this resource. The friend relationship between ClassA and ClassAAccessor allows ClassAAccessor to directly access the protected methods of ClassA.
Design Constraints:
To ensure proper refactoring, several constraints are set:
Refactoring Steps:
Step 1: Introduce an Abstract Interface
Extract the operations that were previously accessible via the friend relationship into a separate interface called InternalInterface. Refactor the relationship between ClassA and ClassAAccessor to make it dependent on this interface rather than using the friend keyword.
Step 2: Move Operations to Interface
Move the operations from ClassA to the InternalInterface. This eliminates the "call" dependency from ClassAAccessor directly to ClassA.
Step 3: Glue Implementation Together
Create a private member variable in ClassAAccessor that points to an instance of InternalInterface. Introduce a method in ClassA that allows setting this member variable to enable ClassAAccessor to access the required internal operations.
Implementation Example:
<code class="cpp">class ClassAAccessor { public: ClassAAccessor(ClassA& classA); void setInternalInterfaceRef(InternalInterface & newValue) { internalInterfaceRef = &newValue; } private: InternalInterface* internalInterfaceRef; }; class ClassA : protected InternalInterface { public: attachAccessor(ClassAAccessor & accessor); };</code>
Advantages of Refactoring:
Disadvantages of Refactoring:
The above is the detailed content of How to Remove a Friend Declaration Without Compromising Design?. For more information, please follow other related articles on the PHP Chinese website!