Home  >  Article  >  Backend Development  >  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?

DDD
DDDOriginal
2024-11-05 10:02:02365browse

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):

<code class="cpp">class ClassA : protected InternalInterface {
    public:
        attachAccessor(ClassAAccessor &accessor) {
            accessor.setInternalInterfaceRef(*this);
        }
};</code>

ClassAAccessor (friend):

<code class="cpp">class ClassAAccessor {
    public:
        ClassAAccessor(ClassA& classA) : internalInterfaceRef(0) {
            classA.attachAccessor(*this);
        }
    private:  
        InternalInterface* internalInterfaceRef;
};</code>

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

The above is the detailed content of How to Refactor a \"Friend\" Dependency Declaration: A Step-by-Step Guide to Removing Excessive Interdependency?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn