Say as an example I have a Player class that has a race via a Race class. These races are fixed in number and are loaded into an array which can be accessed statically.
My question is whether the Player class should have an index ID number which would then need to call the static function getRaceByID(int) to retrieve the Race class to do some internal calculations. Now I could get around having to do this if I was to have the race reference directly in the Player class, but then saving the player to a file becomes problematic. I only want a reference to the Race be stored along with the Player data. Like an ID.
I want to avoid storing a copy of the Race data and instead just reference it. Is there anything I should be doing differently? Are there any patterns to address something like this? Databases deal with IDs, but it doesn’t seem to work very well in OO development. Any help is appreciated, thanks.
class Player
{
Race race;
}
In this case I would need to compare this race to the races in my static array so that I can properly write out the index ID. Another solution is to store the ID in the Race class itself so that I can reference it directly from the Race class like so:
race.getID();
Or would it be better to go with something like this to enforce this relationship:
class Player
{
int raceID;
}
Race r = MyFile.getRaceByID(raceID);
// can now use race
There’s no reason that your ID based concept won’t work. It doesn’t violate any OO principles, and has several benefits. I see no reason NOT to go that route, especially if you’ve already determined that it would work well for you.
As an aside, if you want to avoid having
static_races[player.race_id]scattered throughout your code, a simple wrapper function would suffice in maintaining a more “OO feel” (Psudocode, since you haven’t stated a language:Simple, but effective. No need to over complicate things.