在多大程度上这可能是一个坏的做法? [循环依赖] [英] To what extent can be this a bad practice? [circular dependence]

查看:134
本文介绍了在多大程度上这可能是一个坏的做法? [循环依赖]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(首先,对我的英语很抱歉)

(First and foremost, sorry for my English)

为了避免循环依赖的语法限制,我想知道如果下面提出的解决方案是真的一个解决方案,或者如果它比冒险有更多的缺点(让我支持这种相互依赖是不可避免的):

In order to avoid the syntactic limitation of circular dependence, I want to know if the following proposed solution is really a solution or if it has more disadventages than adventages (let's me suposse that this mutual dependence is inavoidable):

原始情况:

class B;

class A
{
   B needed;
};

class B {};

输出:

B has an incomplete type.

解决方案:

template<typename T = class B>
class tricky_A
{
    static_assert(is_same<T, B>::value, "Too tricky!!");

    T needed;
};

class B {};

using A = tricky_A<>;

int main()
{
   A a;  // At the instantiation point, B isn't an incomplete type.
}

输出:

No problems.

常见的解决方案是使用指针,但是我看到两个问题,需要他们:

The common solution is to make use of pointers, but I see two problems when you really don't need them:

1)如果你决定保留指向其他本地对象的指针,你应该确定(或你的类的用户应该确定)你的对象比保留对象的生命周期短。

1) If you decide to retain pointer to other local objects, you should be sure (or the user of your class should be sure) that the life of your object is shorter than the life of the "retained" object.

2)如果你决定处理动态内存,你应该花费时间保留和破坏内存,此外,它强制您处理异常处理,以使您的代码异常安全。

2) If you decide to deal with dynamic memory, you should spend time reserving and destructing memory, and moreover it forces you to deal with exception handling, in order to make your code exception safe.

*)更长的代码;较小的可读性;更难的

*) Longer code; smaller readability; harder mantenance; etc.

我应该使用这个解决方案还是更好地搜索其他人?

Should I use this "solution" or better to search other one?

:没关系。这不是一个真正的循环依赖,所以,没有什么要问。此问题可以关闭。

EDIT: You are all right. This isn't a real circular dependence, so, there isn't anything to ask. This question can be closed.

EDIT2 :更好的问题

EDIT2: A better question here.

推荐答案

您的设计的前提是错误的。因为你的代码没有循环依赖,没有什么可解决的(除了定位 B 之前 A ),不需要额外的工作。

The premise on your design is wrong. Since there is no circular dependency in your code, there is nothing to fix (other than locating the definition of B before A) and no extra work needs to be done.

如果你修复你的测试用例包含一个真正的循环依赖,你会发现你的 / em>不解决它。因此,基本上你有更多的代码是更复杂,仍然是同样的问题。

If you fix your test case to contain a real circular dependency, you will find out that your solution does not solve it. So basically you have more code that is more complex and still the same problem.

还要注意,处理循环依赖的通过打破它。一旦循环依赖消失了,管理它的需要也消失了。有很少的好设计包含一个真正的循环依赖。

Also note that the correct way of handling a circular dependency is by breaking it. Once the circular dependency is gone, the need to manage it is also gone. There are very few good designs that contain a real circular dependency.

这篇关于在多大程度上这可能是一个坏的做法? [循环依赖]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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