In programming, when does it make sense to have 2 references to the same object (name ambiguity)

133 views Asked by At

In programming, the standard practice is to give each object it's own unique name by assigning it's address to only one reference variable.

If we assign one reference variable to another reference variable, it creates two different names for the same thing. I was asked when doing this would be useful.

When would using ambiguous names be useful? The only reason I could see for doing this is if you need to make a copy of an object's value to prevent overwriting.

1

There are 1 answers

0
Joachim Sauer On BEST ANSWER

What you describe is not ambiguity, it's aliasing (specifically pointer aliasing).

You don't usually do it explicitly, but it can be very useful if you pass a reference/pointer to another method. Then at least two variables (the original one and the parameter) will reference the same object, but for different reasons.

If you do it explicitly, then it's usually because two variables take two different roles.

For example if you're writing code that traverses a tree, you usually start at the root. So the beginning of your code might look like this:

TreeNode rootNode = getTreeRootFromSomewhere();
TreeNode currentNode = rootNode;
while (currentNode != null) {
  ...

In this case currentNode is obviously an alias for rootNode at this point. Later on we will certainly change what currentNode points to, but the first time you enter the loop they point to the same object.