views:

60

answers:

5

I don't know how better to describe this. So take this example.

var a = {
  x: 1,
  y: 2 };

var b = {
  z: 3,
  refA = a };

a.refB = b;

I have a preference that this is sort of behavior is ugly. So at best, I have a personal disagreement with this sort of coding. You should not need to have these types of references, and it leads to code that is difficult to comprehend.

However, does anyone see a technical penalty for doing these sort of references.

+1  A: 

Javascript is a dynamic language. What you are describing, adding a property at runtime, is a feature in this case.

hvgotcodes
+2  A: 

Mutual references (what you call reference loops) are necessary for some data structures. Many trees have links pointing from parent to child and vice-versa; double-linked lists have a prev and next pointer.

Is there a particular reason you don't like this?

lacqui
The reason I don't like this, is methods in A start calling data structures from B and vice versa. So instead of A handling itself and B handling itself, you have each other tapping into the other to do things. This makes it extremely difficult to track down who is doing what where.
Drew
Not necessarily. If you use accessors and mutators (getters if you don't like it or find it ugly, you are not going to be happy as a programmer.
lacqui
Yes I do this a lot, however the code I'm looking at does not do that. A is mutating b and B is mutating A and thusly calling functions to mutate B. My normal practices of parent > child without child doing things to parent prevents this spaghetti code.
Drew
A: 

It's called circular references, and is in some ways necessary or can not be avoided. Best example is a regular dictionary - where you explain the meaning of a word with other words. Or linked lists.

So depening on your use case, it may be of good or evil.

Björn
+1  A: 

I do not think there should be any penalty for reference loop. In some case this is needed too. For e.g. customer and account object. In account object you will have reference to customer (one or many) and in customer you need reference to account (again can be more than one)

Hemang
A: 

There is no performance penalty. The circular references are just pointers to each other, not copies. Like someone else mentioned, sometimes it is necessary to have circular references. Most heirchical structures use circular references to represent parent/child relationships. Sometimes the child needs to know the parent and the parent needs to know the child. It makes it easy to walk up and down the hierarchical ladder so to speak.

Breakskater