best way to reference an object before it is assigned?

和自甴很熟 提交于 2021-02-08 07:28:30

问题


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.


回答1:


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);

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.




回答2:


This is just a first idea, but I think the main approach should be to decouple the class creation from defining their relationships.

Maybe something like this would work (not sure about your exact relationships):

void Connect(SomeClass a, SomeClass b) {
    a.first = b;
    b.snd = a;
}

And use it like:

SomeClass a = new SomeClass();
SomeClass b = new SomeClass();
SomeClass c = new SomeClass();

Connect(a, b);
Connect(a, c);
Connect(c, b);

(That design is still not perfect, but at least makes it clear what happens IMHO)




回答3:


Unfortunately there is no way to realise this as it is a circular dependency.

  • You need a car to go to work (Someclass a = new Someclass(b))
  • You need money to buy a car (Someclass b = new Someclass(c))
  • You need to work to get money (Someclass c = new Someclass(a))

This cannot fit, you have to replace one item with something else. Go by foot, that requires no money!

Same problem with swapping values of 2 variables:

var a = 5;
var b = 2;
var tempvar = a;
a = b;
b = tempvar;

You have to get rid of the depencies or bind them after initialization. This is a logical problem, no programming problem.



来源:https://stackoverflow.com/questions/49940183/best-way-to-reference-an-object-before-it-is-assigned

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!