为什么循环引用被认为有害? [英] Why are circular references considered harmful?

查看:129
本文介绍了为什么循环引用被认为有害?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

解决方案

为什么一个对象引用另一个引用第一个对象的对象是一个坏的设计? 之间的循环依赖不一定是有害的。的确,在某些情况下,它们是可取的。例如,如果您的应用程序处理宠物及其所有者,您将期望宠物类有一种方法来获取宠物的所有者,并且所有者类具有返回宠物列表的方法。当然,这可以使记忆管理变得更加困难(以非GC的语言)。但是,如果循环是固有的问题,那么试图摆脱它可能会导致更多的问题。



另一方面,循环依赖关系模块是有害的。通常表示模块结构不合格,和/或不能坚持原来的模块化。一般来说,具有不受控制的交叉依赖关系的代码库将比使用干净,分层的模块结构的代码更难理解并且难于维护。没有体面的模块,更难预测变化的影响。这使得维护更加困难,并导致由于不适当的修补而导致的代码衰减。



(另外,构建Maven等工具不会处理模块(artefacts)与循环依赖关系。)


Why is it a bad design for an object to refer to another object that refers back to the first one?

解决方案

Circular dependencies between classes are not necessarily harmful. Indeed, in some cases they are desirable. For example, if your application dealt with pets and their owners, you would expect the Pet class to have a method to get the pet's owner, and the Owner class to have a method that returns the list of pets. Sure, this can make memory management more difficult (in a non-GC'ed language). But if the circularity is inherent in the problem, then trying to get rid of it is probably going to lead to more problems.

On the other hand, circular dependencies between modules are harmful. It is generally indicative of a poorly thought-out module structure, and/or failure to stick to the original modularization. In general, a code-base with uncontrolled cross-dependencies will be harder to understand and harder to maintain than one with a clean, layered module structure. Without decent modules, it can be much harder to predict the effects of a change. And that makes maintenance harder, and leads to "code decay" resulting from ill-conceived patching.

(Also, build tools like Maven won't handle modules (artefacts) with circular dependencies.)

这篇关于为什么循环引用被认为有害?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆