Recipe Name:
Collections: Do not expose internal Lists
Description:
Do not expose an internal List 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.List 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.List

Before
public class ListExample {
    private List<String> myList;

    public List<String> getMyList() {
        return myList;
    }
}
After
public class ListExample {
    private List<String> myList;

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