I just worked through an interesting bug in a front-end single page application. The system has the ability to create new items, and one of the attributes of the item is an array of ids. When I created a new item after working with an existing one, ids from the older item were showing up in the new one. Similar issues were happening in several places in the codebase for that interface.
What I eventually realized is that the default attributes are passed into instantiated objects directly -- they are not deep copies. So my code was simply modifying the existing array rather than overwriting it, and as a result my old and new instances were both using the same attribute array of ids.
The takeaway lesson is that complex defaults, such as arrays or objects, should be set in the instantiation method so they are distinct in distinct instances.
What I eventually realized is that the default attributes are passed into instantiated objects directly -- they are not deep copies. So my code was simply modifying the existing array rather than overwriting it, and as a result my old and new instances were both using the same attribute array of ids.
The takeaway lesson is that complex defaults, such as arrays or objects, should be set in the instantiation method so they are distinct in distinct instances.
Comments
Post a Comment