Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a reference to a mutable object value stored in one of the object's fields exposes the internal representation of the object

I'm getting this error when running checkstyle on my code for the following lines:

@Override
public String[] getDescriptions() {
    return DESCRIPTIONS;
}

but DESCRIPTIONS IS NOT mutable. It's defined as:

private static final String[] DESCRIPTIONS = new String[NUM_COLUMNS];

static {
   // In a loop assign values to the array.
   for (int i = 0; i < NUM_COLUMNS; ++i) {
       DESCRIPTIONS[i] = "Some value";
   }
}

This is the complete error message:

"Returning a reference to a mutable object value stored in one 
 of the object's fields exposes the internal representation of
 the object. If instances are accessed by untrusted code, and 
 unchecked changes to the mutable object would compromise security
 or other important properties, you will need to do something 
 different. Returning a new copy of the object is better approach
 in many situations."

Related Question: Link

like image 497
user1071840 Avatar asked Dec 18 '13 00:12

user1071840


People also ask

Are mutable objects passed by reference?

If you pass a mutable object, like a list or a dictionary, it's like pass-by-reference. Again, you can't reassign the parameter to something else, but you can modify the object that you get.

Do not Return references to private mutable class members?

Returning references to internal mutable members of a class can compromise an application's security, both by breaking encapsulation and by providing the opportunity to corrupt the internal state of the class (whether accidentally or maliciously).

Which of the following object Cannot be hashable in Python?

All immutable built-in objects in Python are hashable like tuples while the mutable containers like lists and dictionaries are not hashable. Objects which are instances of the user-defined class are hashable by default, they all compare unequal, and their hash value is their id().


1 Answers

Arrays and some collections are not immutable in the sense that their content still remains mutable.

Immutability in Java only concerns object's reference assignment, not its deep content.

Try this:

@Override
public String[] getDescriptions() {
    return Arrays.copyOf(DESCRIPTIONS, DESCRIPTIONS.length);
}

BTW, caution to java naming convention.. : descriptions, not DESCRIPTIONS

like image 139
Mik378 Avatar answered Nov 09 '22 19:11

Mik378