Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Practice for Returning Object References

Consider this code snippet:

class MyClass{
    private List myList;
    //...
    public List getList(){
        return myList;
    }
}

As Java passes object references by value, my understanding is that any object calling getList() will obtain a reference to myList, allowing it to modify myList despite it being private. Is that correct?

And, if it is correct, should I be using

return new LinkedList(myList);

to create a copy and pass back a reference to the copy, rather than the original, in order to prevent unauthorised access to the list referenced bymyList?

like image 623
chrisbunney Avatar asked Jul 11 '10 21:07

chrisbunney


People also ask

Can reference to an object be returned?

Explanation: This is possible but not always, since the reference being returned may get destroyed with the return of method. This is an undesirable condition, hence it is not always possible to return references. But it is always possible if the referred element is not local to the method.

How the returning by reference is performed?

The major difference is that the pointers can be operated on like adding values whereas references are just an alias for another variable. Functions in C++ can return a reference as it's returns a pointer. When function returns a reference it means it returns a implicit pointer.

When should I return by reference?

You should return a reference to an existing object that isn't going away immediately, and where you don't intend any transfer of ownership.

What does it mean to return a reference to an object?

It means you return by reference, which is, at least in this case, probably not desired. It basically means the returned value is an alias to whatever you returned from the function. Unless it's a persistent object it's illegal. For example: int& foo () {


2 Answers

I do that. Better yet, sometimes I return an unmodifiable copy using the Collections API.

If you don't, your reference is not private. Anyone that has a reference can alter your private state. Same holds true for any mutable reference (e.g., Date).

like image 55
duffymo Avatar answered Oct 15 '22 10:10

duffymo


It depends on what you want.

Do you want to expose the list and make it so people can edit it?

Or do you want to let people look at it, but not modify it?

There is no right or wrong way in this case. It just depends on your design needs.

like image 34
jjnguy Avatar answered Oct 15 '22 10:10

jjnguy