Reputation: 3181
Should getters just return the object:
public MyObject getMyObject() {
return myObject;
}
Or should it make a copy of the object it's returning and return the copy?
public MyObject getMyObject() {
MyObject tempObject;
// call setters to set its attributes
return tempObject;
}
High school "CS" courses here aren't detailed enough. My teacher never talked about classes, objects, and references.
Upvotes: 2
Views: 93
Reputation: 28697
The only difference is that while returned primitives are "immutable" by nature, returning an object directly like this could allow the caller to change properties on it (assuming that MyObject
is mutable), possibly affecting the internals of your class's implementation. (Code analysis tools like FindBugs check for exactly this. Primitives are actually mutable, but when returned from a class, there is no way to update the class's value through the returned primitive.) That considered, it's usually a safer bet to return a copy / clone - understanding there may be a performance penalty involved in doing this.
With whatever option you choose, please document what your class or individual methods do using Javadoc.
Upvotes: 3
Reputation: 3658
This depends on what you're trying to do.
In general, though, you just want a reference to the object, and you use your first code example. For example, Swing components have a method called getTopLevelAncestor()
. It's completely useless to have a copy of the parent component--what's wanted is a reference to the child's actual parent.
Returning a copy is not standard, and should only be used under very specific (and well-documented) circumstances. Other people using your code will not expect to get copies of objects.
Upvotes: 4