Sonar Violation: Security - Array is stored directly

后端 未结 7 2173
广开言路
广开言路 2020-11-27 04:53

There is a Sonar Violation:

Sonar Violation: Security - Array is stored directly

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


        
7条回答
  •  囚心锁ツ
    2020-11-27 05:29

    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.

提交回复
热议问题