Recipe Name:
Do not expose internal array
Description:
Do not expose an internal array as it is mutable
Level:
warning
Language:
  • java
Tags:
  • security
  • Java basic
  • quality
Documentation

Exposed internal arrays are still mutable. This violates the object encapsulation rule for the internal property.

Exposing arrays that are internal to the application enables users to modify their contents, possibly leading to an unintended internal state which in turn can lead to undesired behaviour. To prevent exposing internal data structures, a copy of the object should be returned instead so that any modifications to the returned object do not impact the internal state of the called class.

Before
class Dto {
    protected String[] values;

    public String[] getValues()
    {
        return values;
    }
}
After
class Dto {
    protected String[] values;

    public String[] getValues()
    {
        return Arrays.copyOf(values, values.length);
    }
}
Resources
Recipe
id: scw:java:internal-arrays
version: 10
metadata:
  name: Do not expose internal array
  shortDescription: Do not expose an internal array as it is mutable
  level: warning
  language: java
  cweCategory: 200
  enabled: true
  descriptionFile: descriptions/Donotexposeinternalarray.html
  tags: security;Java basic;quality
search:
  reference:
    allOf:
    - in:
        return:
          type: '{{{ type }}}'
          value:
            reference:
              name: '{{{ name }}}'
    - in:
        typeDeclaration:
          member:
            field:
              allOf:
              - type: java.lang.Object[]
              - type: '{{{ type }}}'
              modifier:
                not:
                  anyOf:
                  - is: final
                  - is: public
              name: '{{{ name }}}'
availableFixes:
- name: Return a copy of the array
  actions:
  - rewrite:
      to: java.util.Arrays.copyOf({{{ . }}}, {{{ . }}}.length)
      target: self