Re: Complex object graph and "this" escaping constructor.
Lasse Reichstein Nielsen wrote:
Daniel Pitts <newsgroup.spamfilter@virtualinfinity.net> writes:
This is especially troublesome with circular references, which I've
been told should be avoided (probably for just this reason).
Unfortunately, I don't see a rule that can be applied to
systematically avoid circular during initialization. For my
particular case.
I have a class Robot, which has a Computer object, which has a Memory
object and a Bus object. The Computer needs to know about the Robot,
and visa versa.
Why? What is the relationship between Robot and Computer that the
references model? Does that relationship really need to be created at
the time the Robot and/or Computer is created?
Can a computer not be moved to another computer?
Are the Robot and Computer really separate entities, or does a Robot
have a Computer aspect to it ... e.g., by implementing a Computer
interface?
Really, a computer is an aspect of a Robot, but it is complex enough
that I'd like to separate it out. A robot also has a weapon, heatsink,
engine, shield, etc... The computer is the one that actuates all of
these, so needs a reference either to those, or to the computer which
owns them.
Of course, I realized after-the-fact that I should probably just use an
event driven system instead. Eg. the weapon registers itself as a
listener on the appropriate bus channel of the computer.
I can instantiate them separately, and then pass the
references of each other to each other, but the Computer implementor
would have to explicitly know that they can't access the Robot object
during that reference exchange.
"Computer" sounds more generic than something that inherently knows
about a Robot.
In this simulation, it is coupled to the robot. However, using the event
model I can decouple it.
Of course, I could just be confusing matters and making this into a
bigger problem than it is. Any thoughts?
I have this problem with MVC all the time :)
Yeah, that's the other issue I'm dealing with on the same project ;)
Thanks.
--
Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>