tichtich wrote:Ah, I didn't think of that. But now I'm surprised the compiler doesn't object to Game's "new HexProc(this)", since it can see perfectly well that this is a case of passing a self-reference in a constructor.
Well, I was reminded of passing this when I noticed that Netbeans underlined and put a light bulb next a row which passed this in a constructor. But now I don't see those light bulbs anymore.
I think the problem is only with passing a self-reference from a constructor, not to one, so I guess you could still get rid of Battleinit, put the initialisation in Battle's constructor instead, and call "new Battle" from Game.init. Nevertheless, the fact that we can't initialise in Game's constructor (and have to get Gui involved in calling init) is a minus for this system IMO.
Well, having said what I said, I have looked at various sources around the net and some say that passing this in constructor is ok if you are cognizant of the fact that your object is not yet constructed and you don't for example call any non-static functions using that reference.
Yes, I had in mind a static variable, but there's no need to add an extra variable. Just add "static" to the existing declaration of game. I just tried it, and it seemed to work.
Still, it doesn't smell right. We would have sub-objects of Game going over its head to Gui to get access to its data! I'm sure purists wouldn't like it.
On one hand, this would be convenient, but then as you say it does sound backward.
I've gone back to thinking about why HexProc and Battle are separate classes in the first place.
<clip>
I think what we really want is to put some methods in a separate file, but not in a separate class. Java doesn't provide that option, so we're trying to find a way of splitting into classes with a minimum of overhead.
If we do stick with your current system, there are two variations. You've used a mixture of both.
1. Pass only game to the constructor, which stores it. The methods can then access specific fields via getters, e.g. game.getUnitTypes().
2. Pass specific fields as parameters to the constructor, and store them, e.g. with "this type_data = type_data". They can then can be accessed directly.
<clip>
Sorry I don't have a strong recommendation for how to proceed. I can't make up my own mind.
Passing fields as parameters could get out of hand quickly. I would vote we pass game only.
- If we don't pass game at all, then presumably we avoid the problem of passing a self-reference from a constructor. (Or is there a problem with passing references to one's own fields from a constructor?)
The problem with passing this is just the possibly unintialized members, if a field was not initialized it would have a possibly undefined value.