Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sonar Violation: Security - Array is stored directly

Tags:

java

sonarqube

There is a Sonar Violation:

Sonar Violation: Security - Array is stored directly

public void setMyArray(String[] myArray) {    this.myArray = myArray;  }  

Solution:

public void setMyArray(String[] newMyArray) {    if(newMyArray == null) {      this.myArray = new String[0];    } else {     this.myArray = Arrays.copyOf(newMyArray, newMyArray.length);    }  } 

But I wonder why ?

like image 633
Junchen Liu Avatar asked Jul 20 '12 14:07

Junchen Liu


2 Answers

It's complaining that the array you're storing is the same array that is held by the caller. That is, if the caller subsequently modifies this array, the array stored in the object (and hence the object itself) will change.

The solution is to make a copy within the object when it gets passed. This is called defensive copying. A subsequent modification of the collection won't affect the array stored within the object.

It's also good practice to normally do this when returning a collection (e.g. in a corresponding getMyArray() call). Otherwise the receiver could perform a modification and affect the stored instance.

Note that this obviously applies to all mutable collections (and in fact all mutable objects) - not just arrays. Note also that this has a performance impact which needs to be assessed alongside other concerns.

like image 58
Brian Agnew Avatar answered Oct 13 '22 08:10

Brian Agnew


It's called defensive copying. A nice article on the topic is "Whose object is it, anyway?" by Brian Goetz, which discusses difference between value and reference semantics for getters and setters.

Basically, the risk with reference semantics (without a copy) is that you erronously think you own the array, and when you modify it, you also modify other structures that have aliases to the array. You can find many information about defensive copying and problems related to object aliasing online.

like image 40
ewernli Avatar answered Oct 13 '22 10:10

ewernli