Recommendation 111: Avoid bidirectional coupling
Bidirectional coupling refers to the mutual reference between two types. The following code is a typical bidirectional coupling:
class A { private b b; Public void MethodA () { b.methodb (); } } class B { private a A; Public void MethodB () { A.methoda (); } }
Two-way coupling under the same project, there will not be too many problems, only the design problems. However, if the two classes are in a different project, you must consider decoupling, because. NET does not allow cross-referencing between projects. If you try two items with each other, an error will appear.
The common decoupling method is to extract an interface. If the type A and B are in two projects, then the extracted interface should be placed in the new project, and then the two projects where A and B are located will refer to the project where the interface is located respectively.
The decoupled code looks like this:
Interface Isample { void MethodA (); } class A:isample { private b b; Public void MethodA () { b.methodb (); } } class B { isample A; Public void MethodB () { A.methoda (); } }
Interface Isample regulates the behavior of type A, while having type a inherit from Isample. In type B, we program the interface, that is, field A in B is no longer a type, but instead modifies it to the isample type.
In general, there should be no bidirectional coupling between types, and refactoring should be considered if such a situation arises. There are third-party frameworks that support decoupling projects, such as unity and Spring.net in the Microsoft Enterprise Library. In the actual coding, consider using these frameworks to design our projects.
Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia
157 recommendations for writing high-quality code to improve C # programs--Recommendation 111: Avoid bidirectional coupling