The Setup
My Java code contains two objects: a Group and a Person. Each Group can contain references to multiple Person’s, but each Person can only belong to one Group.
The colour of each Person’s sweatshirt is derived from their Group’s colour. (Note: If they don’t belong to a Group, their sweater is gray.)
When I draw a Person on-screen, I take in the Person themselves and a Color.
The Code
Person
public class Person {
Color sweatshirtColor = Color.gray;
Group belongsToGroup = null;
public void setGroup(Group g) { belongsToGroup = g; }
}
Group
public class Group {
Color color = Color.red;
List<Person> people = new ArrayList<Person>();
// ... setters for adding and getting people
}
Draw
public void draw(Person dudette, Color shirtColor) { //... }
The Problem
Group and Person both reference each other – I’m afraid that one might get out of sync with the other. My draw code has to be fixed (because it’s external), but is there anything obvious I’m doing wrong in this design?
EDIT: One more note – Groups can change throughout the program. A Person’s Group depends on their location so they are constantly switching Groups.
You could introduce setters to each class that will allow either entity to modify the other and itself so that they never get out of synch. E.g.
You can do the same for adding group members.