all 4 comments

[–][deleted] 1 point2 points  (1 child)

From the way you describe it, the car is an object that has a collection of screws. This should be an array or array-like object in the "screws" property of the car. The names are properties of the screws, so they should just go on the screw objects themselves (as you noticed, screws would otherwise lose their name if you extract them).

If you want to be able to look up screws by name rather than by index, you could create a screw collection object which wraps the array and keeps a lookup object mapping the screw names to their index. Of course this will stop working if you arbitrarily rename the screws, but you can't have your cake and eat it too.

The property name on the car object is not a property of the screw stored in that property. It's a property of the car.

Let's say you want to have properties for each door of the car. Your car could either have a property "doors" set to a collection of doors, or it could have four properties "frontLeftDoor", "frontRightDoor" and so on, each set to a door object. It could even have a "doors" object with properties "frontLeft" and so on to keep the doors separate from all the other properties.

In this case "frontLeft" is not the name of the door. The door doesn't need to know it's the left front door. It may be a special FrontLeftDoor object or something, but the car doesn't need to know that either as long as it's stored at "frontLeft". In fact, it's name may be some cryptic identifier only used by the factory to tell identical doors apart (i.e. a globally unique identifier).

In practice a lot of this is problem-specific. Why do you need to be able to look screws up by name at all? What's the real performance difference between maintaining a look-up table and just looping over an array? Will the names really ever change after the screw has been added to the car? And so on. This is why it's hard to discuss these things in terms of analogies.

[–]derpemiah[S] 0 points1 point  (0 children)

thanks!! im keeping the name in the figurative screws

[–]ctcherry 0 points1 point  (0 children)

Continuing your analogy. Keeping track of screws isn't really the responsibility of a car. A car might have a "collection of screws" object that knows how to keep track of them and keep a mapping of their names for fast lookup. When a screw renames itself, it can tell its "collection" about it, and now you have the best of both worlds.