I have “part” objects and “material” objects. Each part has at most 1 material assigned to it. Each material is assigned to 0 or more parts. It’s a DAG with 2 levels.
Should each part object have a reference to its material? Or would it be better to just store the material name or index. Or is there another way besides a database?
The first way means multiple references to the same material object, which seems bad, but how bad?
The second way seems ugly because numerical indices may not get updated correctly, or if referencing materials by name it requires string comparisons. It’s also reinventing object references that are already available in the language.
Go with the reference. It’s quick and uses little memory and you’ll need it. (I do assume you’ll actually use it. A different or additional option would be to keep a list of parts references for each material. But don’t do this if you don’t need it.)
Storing the material name or index will use more space and cost you a lot more when you try to get hold of the material’s object. In fact, the cheapest way to get a part’s material’s name is to use a reference to get the material and get the name or index from the material.
Don’t use names and indexes internally in your program. They do have to be used (and stored in your program) to get things from databases and other programs. (“Other programs”, in practice, means sockets and such and flat files–originally the data came from another program or another session of this program.) And you do have to maintain your references: if the material is removed, all references to it have to be changed. Or you could mark the material as deleted (works well with garbage collection, but watch for re-adds).
And to contradict myself: I have used names instead of references on rare occasion because they work well when materials (to use your case as an example) are being continually added and deleted. If I identify something as “Lumber”, a material of that name can be deleted and added 100 times without, at the end of the day, affecting my parts’ usage of it.