should a getter of a private property return a reference to the property or the value of the property (or a clone if the property is an object).
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If the property has a primitive type (string, number, boolean) or a reference to an immutable object (
String,Number), the answer is that you return the value/reference directly, since there’s nothing the caller can do with it that will change your object’s state.If the property has a reference type to a mutable object (an array, an
Object, aDate, lots and lots of other things), it depends on whether you want the caller to be able to change the properties on your object’s copy of it. If you do, return the reference. If not, clone it.For example, let’s assume an object with a private array and some operations you can perform on that array:
(Note that this is not meant to be a glorious example of object design. 🙂 )
Now you want to add a
getArrayoperation. You can do that in two ways:You can return a reference to the array:
…which means the caller can do all sorts of things to it (like remove items from it, an operation the object didn’t previously support) that will change your object’s state (because you’ve given them direct access to the formerly-private array).
Or you can return a clone of the array:
…which means the caller can’t do anything to the private array, they can only operate on the copy of it you gave them.