Home > Software design >  When should a method return a new object instead of a reference in Java?
When should a method return a new object instead of a reference in Java?

Time:03-18

Let's take this sample Person class from which we want to return the "Details"

public class Person() {
    private Details details;
...

When should I do this:

return new Details(this.details);

Instead of this:

return this.details;

CodePudding user response:

Depends entirely on your use case. In a regular getter case, you'd just return the this.details reference.

I am assuming the constructor to which you are passing the this.details reference is meant to be a copy constructor that's supposed to shallow or deep copy the object (please clarify if that's not what you meant). You'd want to copy if you don't want the user of your method to make changes to your object but to work with a separate copy (how separate depends upon the depth of your copy).

CodePudding user response:

In general it is best not to return references to objects unless they and their fields (and their fields) are immutable. Consider this example:

class Foo {
    private int[] array = new int[];
    public int[] getArray() {
       return Arrays.copyOf(array, array.length);
    }
}

This makes a defensive copy of the returned information so the user may not change the original. If you simply returned the array reference the internals of the array and thus the Foo instance could be altered.

  • Related