分配对象之前引用对象的最佳方法? [英] best way to reference an object before it is assigned?

查看:43
本文介绍了分配对象之前引用对象的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编码与透明度和概述有关.因此,我很想调用在类的构造函数中尚未分配的对象.听起来像是一个愚蠢的主意,所以在这里举个例子(无论如何可能还是愚蠢的):

for me coding is a lot about clarity and overview. Therefore i would love to call objects that aren't already assigned in the constructor of a class. Sounds like an stupid idea so here an example (might be stupid anyway):

// this doesn't work but looks clear
SomeClass a = new SomeClass(b, c);
SomeClass b = new SomeClass(a, c);
SomeClass c = new SomeClass(a, b);


// this functions but has bad overview:
SomeClass a = new SomeClass(null, null);
SomeClass b = new SomeClass(a, null);
SomeClass c = new SomeClass(a, b);
a.first = b;
a.snd = c;
b.snd = c;

底部还有更好的方法吗?

Is there any nicer way to the one on the bottom?

随着半边数据结构的实现,对此的需求增加了,在该结构中,边缘对象存储了对另一个边缘对象的上一个参考和下一个参考.我认为循环引用不是很好,但是例如下一个列表对于每个下一个项目也具有这种针对性.

The need for this rised with the implementation of the halfedge data structure where an edge object stores a prev and a next reference to another edge object. I think circular references aren't nice but lists for example also have such refenences for each next item.

推荐答案

不是在构造函数中分配边,而是在单独的方法中进行:

Instead of assigning the edges in the constructor, do it in a separate method:

SomeClass a = new SomeClass();
SomeClass b = new SomeClass();
SomeClass c = new SomeClass();
a.SetEdges(b, c);
b.SetEdges(a, c);
c.SetEdges(a, b);

这看起来更具可读性.您可能需要添加一些保护机制,以防止在分配边缘之前使用该类.但是如果您在构造函数中接受null,情况也会如此.

This looks much more readable. You will probably need to add some guard mechanism to prevent the class from being used before the edges are assigned; but that would also be the case if you are accepting nulls in the constructor.

这篇关于分配对象之前引用对象的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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