1

I'm getting the following violation reported by Sonar: May expose internal representation by returning reference to mutable object.

It's because I'm returning a String[] from a getter.

I know what the problem is and how to solve it but going through several thread on stackoverflow I noticed that seems to be happen for String[] and Dates for example:

Malicious code vulnerability - May expose internal representation by returning reference to mutable object

Malicious code vulnerability - May expose internal representation by incorporating reference to mutable object

But given the reason why that happens which is returning a reference to an object whose internal state could be changed by the caller. Shouldn't that violation be raised for every getter returning a mutable object?

For example:

public List<String> getList() { return list; }

public Foo getFoo() { return foo; } //where foo is just a random object with getters and setters...

The caller could change the state of the returned objects. Shouldn't sonar report the same for those?

Many thanks, Francisco.

Community
  • 1
  • 1
secuf
  • 35
  • 1
  • 5

1 Answers1

4

Sonar is not smart enough to know if an object is mutable or not. Especially if you're returning a List, it can't tell if what you're actually returning is an ArrayList, an ImmutableList or an unmodifiable list. So it doesn't emit any warning to avoid flooding you with false positives.

Arrays and Date, on the other hand, are well-known standard classes that are mutable, and for which it can safely emist this warning.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Although, having fought with this issue on multiple projects - this is BS. Date is indeed mutable in Java 7 and earlier and while one could argue should not be, is in keeping with accepted frameworks like Hibernate and JSF that break information hiding anyway. Most web applications, for example have fully mutable get/set Date methods - so what is the difference? It is irrelevant unless the method is exposed to a PUBLIC SERVICE. If you don't trust the public methods inside your own JVM that allow get/set Date anyway ... then every public mutator is a vulnerability... – Darrell Teague Jul 31 '14 at 12:30