Search code examples
javascriptobject

is it good to "store" object in object


Is it better to store objects or reference to objects in an other object ? Let me explain with an example.

I have one object "Team" and one object "Unit" the unit belong to the team. I want to "store" the object "unit" in my object "team".

  1. I can do something like this: the units are stored in the team object

    // class Team
    function Team() {
        this.units = [];
    }
    // class Unit
    function Unit(team) {
        team.units.push(this);
    }
    myTeam = new Team();
    units = [];
    units[units.length] = new Unit( myTeam );
    
  2. Or something like this: the units id are stored in the team object

    // class Team
    function Team() {
        this.units = [];
    }
    // class Unit
    function Unit(team, id) {
        team.units.push(id);
    }
    myTeam = new Team();
    units = [];
    units[units.length] = new Unit( myTeam, units.length );
    

is it understandable ?


Solution

  • If your concern is that storing objects will take up more memory, this is incorrect.

    An object in Javascript is a unit of data stored somewhere in memory, but when you are adding objects in the first code sample you are merely adding a reference to that piece of memory: you are not creating a copy of the object (which would double memory usage). There is no performance benefit in the second approach as far as storage is concerned.

    Now, let us address design. Many times, I have used associating arrays and the like, where the id of objects are not part of their set of fields. This has invariably lead to more complicated code because there always came a time where I needed to pass the object somewhere but also its id. Unless there are special circumstances that dictate otherwise, it usually makes perfect sense that the id be considered to be part of the object. A design decision that makes sense at the conceptual level is likely to lead to better design choices further on.

    So my vote is definitely for alternative 1.