Java – reference classes are constructed by classes
I am a web developer (game developer as a hobby) and I have seen myself using the following example several times (both are developing server architecture and video game development.) It looks really ugly, but I don't know if I have a job I will give an example in game development, because this is what I have noticed recently This is the RPG I've been working on Every time a battle is launched, the combat engine will form both sides of the combatants Each fighter sets an artificialligence object associated with a given fighter, which is responsible for indicating the movement of players who do not receive explicit commands:
public class Combatant {
ArtificialIntelligence ai = null;
public Combatant()
{
// Set other fields here.
this.ai = new ArtificialIntelligence(this);
}
}
Here's what I don't like: the internal intelligence takes action during construction, because it needs some combat areas to specify appropriate actions Therefore, for convenience, I keep the reference to the warfighter as a reference to the artificialligence object, but the object contains a reference to the AI object itself! It creates this strange recursion, but I don't know how to solve it AI objects need a lot of fields specific to combatants, so that's why I pass them in the whole object, but I don't like the object to include a reference field to the AI field contained in the upper combatant, which is contained in the upper AI class Is this a bad practice, or am I just thinking?
Solution
Although there is no "design" problem here, this is just a reference you pass - an important consideration is that all fields should be initialized before passing it to another class Otherwise, another class will access this class in a potentially inconsistent state This is sometimes called getting this "escape" from the constructor
Don't do that
public class BadCombatant {
ArtificialIntelligence ai = null;
String someField;
public BadCombatant() {
this.ai = new ArtificialIntelligence(this);
// Don't do this - ArtificialIntelligence constructor saw someField as null
someField = "something";
}
