Why is it a bad design for an object to refer to another object that refers back to the first one?
相关问题
- how to define constructor for Python's new Nam
- Generic Generics in Managed C++
- Keeping track of variable instances
- How to Debug/Register a Permanent WMI Event Which
- Object.create() bug?
Because now they're really one single object. You can't test either one in isolation.
If you modify one, it's likely that you affect its companion as well.
Such an object can be difficult to be created and destroyed, because in order to do either non-atomicly you have to violate referential integrity to first create/destroy one, then the other (for example, your SQL database might balk at this). It might confuse your garbage collector. Perl 5, which uses simple reference counting for garbage collection, cannot (without help) so its a memory leak. If the two objects are of different classes now they are tightly coupled and cannot be separated. If you have a package manager to install those classes the circular dependency spreads to it. It must know to install both packages before testing them, which (speaking as a maintainer of a build system) is a PITA.
That said, these can all be overcome and its often necessary to have circular data. The real world is not made up of neat directed graphs. Many graphs, trees, hell, a double-linked list is circular.
The .NET garbage collector can handle circular references so there is no fear of memory leaks for applications working on the .NET framework.
It is completely normal to have objects with circular references e.g. in a domain model with bidirectional associations. An ORM with a properly written data access component can handle that.
Refer to Lakos’s book, in C++ software design, cyclic physical dependency is undesirable. There are several reasons: