I'm a web dev (game dev as a hobby), and I've seen myself use the following paradigm several times. (Both in developing server architecture and with video game dev work.) It seems really ugly, but I don't know a work around. I'll give an example in game dev, because it's where I recently noticed it. This is an RPG that I've been working on. Every time a battle is launched, the CombatEngine creates two parties of Combatants. Every Combatant sets up an ArtificialIntelligence object that's associated with the given Combatant, which is in charge of dictating moves for players which don't receive an explicit command:
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 inner field (ArtificialIntelligence) takes a Combatant during construction, because it needs some of the Combatant fields in order to dictate appropriate actions. So, for convenience, I keep a reference to the combatant passed in as an arg to the ArtificialIntelligence object, but that object contains a reference to the ai object itself! It creates this weird recursion, but I don't know how to work around it. The AI object needs a good deal of the fields that are specific to combatant, so that's why I passed in the entire object, but I don't like how the object then contains the reference to the ai field which is contained in the overlying combatant field, which is contained in the overlying ai class. Is this bad practice, or am I simply over thinking it?