Swapneel
Swapneel

Reputation: 196

Sonar scan - Mutable members should not be stored or returned directly

When I do a sonar scan I get the vulnerability "Mutable members should not be stored or returned directly". The resolution for this is also provided where it is mentioned that we should clone the mutable object or return unmodifiable list. However if I clone the object and later on if I want to update the value then how can I access the original object because I have returned the cloned object? Any thoughts on this will be appreciated. Thanks in advance

Upvotes: 1

Views: 6482

Answers (1)

G. Ann - SonarSource Team
G. Ann - SonarSource Team

Reputation: 22804

However if I clone the object and later on if I want to update the value then how can I access the original object because I have returned the cloned object

You don't. At least not from the caller.

I'll go out on a limb here and say we're talking about a list, so:

public class MyClass {
  private List<String> strings;

  public List<String> getStrings(){ 
    // returns a copy, so member list is still intact
    return new ArrayList<String>(strings);
  }

  public void addString(String newString) {
    strings.add(newString);
  }

  public void dropString(String oldString) {
    strings.remove(oldString);
  }

  public void replaceString(String oldString, String newString) {
    dropString(oldString);
    addString(newString);
  }
}

In other words, you control access to member actions through the owning class. If you truly want a public member that anyone can get and update (not that I recommend that) then drop the getter and make the member public.

Upvotes: 5

Related Questions