"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Refactor a \"Friend\" Dependency Declaration: A Step-by-Step Guide to Removing Excessive Interdependency?

How to Refactor a \"Friend\" Dependency Declaration: A Step-by-Step Guide to Removing Excessive Interdependency?

Published on 2024-11-21
Browse:149

How to Refactor a \

How to Refactor a "friend" Dependency Declaration

Background

One may encounter a scenario where removing a "friend" dependency between two classes is desired, particularly due to concerns about excessive interdependency, maintenance issues, and outdated UML standards.

Step 1: Introduce an Abstract Interface

Extract the methods exposed by the "friend" class and create a new abstract interface. Establish a dependency relationship from the "friend" class to the interface and a "call" dependency from the other class to the interface.

Step 2: Move Operations to the Interface

Move the operations that make up the "call" dependency from the dependent class to the abstract interface. Make the interface extend a protected constructor for inheritance purposes and hide the protected generalization association between the dependent class and the interface.

Step 3: Glue Implementation Together

In the final step, create a method in the "friend" class to pass a reference of the abstract interface to the dependent class. Call this method from the dependent class during initialization to establish the necessary connection.

Implementation

ClassA (provider):

class ClassA : protected InternalInterface {
    public:
        attachAccessor(ClassAAccessor &accessor) {
            accessor.setInternalInterfaceRef(*this);
        }
};

ClassAAccessor (friend):

class ClassAAccessor {
    public:
        ClassAAccessor(ClassA& classA) : internalInterfaceRef(0) {
            classA.attachAccessor(*this);
        }
    private:  
        InternalInterface* internalInterfaceRef;
};

Advantages

  • Removes unnecessary dependency between classes
  • Conforms to modern UML standards
  • Enforces access control by hiding internal operations from the public

Limitations

  • May increase code complexity
  • Requires abstract interfaces, impacting performance and memory footprint
  • UML representation of protected generalization relationship can be challenging
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3