I've got two classes that go together, but at any given time an object of a given class might or might not be partnered with an object of the other class, and the partners might change over the course of the program.
I want each object to be able to access its partner if it has one, and I want to make sure that both objects keep accurate records of their current partner.
I've come up with something that seems to work (below), but it takes three function calls to avoid getting caught in an infinite loop, and it just seems kind of messy. Is there a better way that I'm not seeing?
(By the way, this is C#, so all of those variables are references. In case it wasn't obvious.)
class Horse {
private Carriage existingCarriage;
public Horse(int num) { horseNumber = num;}
public void setCarriage(Carriage newCarriage) {
if(existingCarriage != null) {
Carriage temp = existingCarriage;
existingCarriage = null;
temp.setHorse(this);
}
existingCarriage = newCarriage;
}
}
//pretty much the same thing with "Horse" and "Carriage" switched.
class Carriage {
private Horse existingHorse;
public Carriage() {}
public void setHorse(Horse newHorse) {
if(existingHorse != null) {
Horse temp = existingHorse;
existingHorse = null;
temp.setCarriage(this);
}
existingHorse = newHorse;
}
}