问题
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