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

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

问题描述

为什么一个对象引用另一个引用第一个对象的对象是一种糟糕的设计?

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

推荐答案

之间的循环依赖不一定有害.事实上,在某些情况下它们是可取的.例如,如果您的应用程序处理宠物及其主人,您会期望 Pet 类具有获取宠物主人的方法,而 Owner 类具有返回宠物列表的方法.当然,这会使内存管理更加困难(在非 GC 语言中).但如果循环性是问题所固有的,那么试图摆脱它很可能会导致更多的问题.

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.

(此外,像 Maven 这样的构建工具不会处理具有循环依赖关系的模块(工件).)

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

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

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