Recipe Name:
Collections: Do not expose internal Sets
Description:
Do not expose an internal Set as it is mutable. Return a copy or immutable view.
Level:
marked_information
Language:
  • java
Tags:
  • security
  • Java basic
  • quality
Documentation

Class methods should return immutable copies of private member variables of type java.util.Collection to prevent external changes to the state of the object. This is the encapsulation principle of OOP.

Returning an instance's private field of type java.util.Set allows external manipulation of the internal state of an instance of the class because the collections are mutable. This can lead to unexpected program behavior when external classes manipulate data in the collection, especially in multi-threaded situations. Class methods should return immutable copies of private member variables of type java.util.Set

Before
public class SetExample {
    private Set<String> mySet;

    public Set<String> getMySet() {
        return mySet;
    }
}
After
public class SetExample {
    private Set<String> mySet;

    public Set<String> getMySet() {
        return java.util.Collections.unmodifiableSet(mySet);
    }
}
Resources
Recipe
id: scw:java:internal-set
version: 10
metadata:
  name: 'Collections: Do not expose internal Sets'
  shortDescription: Do not expose an internal Set as it is mutable. Return a copy or immutable view.
  level: marked_information
  language: java
  cweCategory: 200
  enabled: true
  descriptionFile: descriptions/DonotexposeinternalCollection-set.html
  tags: security;Java basic;quality
search:
  return:
    in:
      typeDeclaration:
        member:
          field:
            modifier:
              matches: (private|protected)
            name: '{{{returnValue.name}}}'
            type:
              reference:
                matches: java.util.Set.*
              checkInheritance: true
    value:
      reference:
        name: '{{{returnValue.name}}}'
availableFixes:
- name: Return an unmodifiable Set
  actions:
  - rewrite:
      to: return java.util.Collections.unmodifiableSet({{{ returnValue }}});