SonarQube: Mutable members should not be stored or returned directly

Viewed 1633

This is my code so far:

public class RestApplication extends Application {

  private final Set<Class<?>> resourceSet;
  public RestApplication() {
    this.resourceSet = new HashSet<Class<?>>();
    resourceSet.add(PCardController.class);
    resourceSet.add(PricingController.class);
    resourceSet.add(TransactionFeedController.class);
    initializeMaps();
  }

  @Override
  public Set<Class<?>> getClasses() {
    return resourceSet;
    // ...
  }   // Added by edit!
  // ...
}     // Added by edit!

SonarQube says that the return of a copy is a resource set.
How can I do that?

3 Answers

you can return a new HashSet:

@Override
public Set<Class<?>> getClasses() {
    return new HashSet<>(resourceSet);
}

Alternatively make the result unmodifiable; less nice usage, better footprint & speed.

@Override
public Set<Class<?>> getClasses() {
    return Collections.unmodifiableSet(resourceSet);
}

This error is because Java returns by reference in some situations. Here's a test to demonstrate pass by reference. The list.size() returns 3.

List<String> list=new ArrayList<String>();;

List<String> getList(){
    list.add("hello");
    return list;
}
@Test
public void run(){
    getList().add("hey");
    List<String> list = getList();
    list.size();
}
Related