Sonar Violation: Security - Array Is Stored Directly

Sonar Violation: Security - Array is stored directly

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.

Sonar Violation: Security - Array is stored directly - Why only arrays?

Sharing mutable state should be avoided since it can cause error in your program. Especially if you are working in multi threaded environment. Also it can make you program much less readable. That's why communication throw modifying same state should be at least minimize.

Coping collections and arrays as well as dates are common practice to make sure that you don't use in your class/thread same object that was provided from other object/thread.

Security - Array is stored directly

Not sure what Sonar is thinking but defensive shallow copying with clone() should work fine for arrays, as would Arrays.copyOf and System.arrayCopy().

On the other hand, since you are already calling the array a list: selectedObjectsList, you could also make it an actual list and refactor a bit:

public final void setSelectedSchedules(List<ScheduleDTO> selectedSchedules) {
this.selectedSchedules = selectedSchedules != null ? new ArrayList<ScheduleDTO>(selectedSchedules) : null;
}

Sonar Violation: Security - Array is stored directly when using byte[]

You could use the following to resolve the issue with byte[]

value.clone()


Related Topics



Leave a reply



Submit