How to solve sonarqube issue based on bug to return a copy

31 views Asked by At

how to solve this issue return a copy of "deductionfrequency". code mentioned below getter method

type : Vulnerability

tags : cert,cwe,unpredictable

issue : Return a copy of "deductionfrequency".

code : public List<String> getDeductionfrequency() { return deductionfrequency; } rule : squid:S2384

your text

I need solution to return a copy for that what changes i have to do in code

1

There are 1 answers

1
Cedric On

The answer depends of what do you want exactly do with the code that consume getDeductionfrequency().

If you want your customer can't change the list (add / change / remove element), so you must do :

public List<String> getDeductionfrequency() { 
    return deductionfrequency.clone(); 
}

Why ? Because with this you can protect your data. If you just return the list without clone, the pointer returned is directly your list, that permit to modify there content.

If you want client can change the list, you can just make your list public directly as a class property.

Sonar give you some explaination when you click on the rules with uncompliant and compliant sample. There is the message source code : https://github.com/joansmith/sonar-java/blob/master/java-checks/src/main/resources/org/sonar/l10n/java/rules/squid/S2384.html