0

I got Fortify findings back and I'm getting a null dereference. I think I know why I'm getting it , just wanted to know what would be the best way to fix the issue. Here is a code snippet:

public class Example{
    private Collection<Auth> Authorities;
    public Example(SomeUser user){
        for(String role: user.getAuth()){ //This is where Fortify gives me a null dereference
            Authorities.add(new Auth(role));
        }
    }

    private List<String> getAuth(){
        return null;
    }
}
shmosel
  • 49,289
  • 6
  • 73
  • 138
JLo
  • 7
  • 2

1 Answers1

1

getAuth() should not return null. A method returning a List should per convention never return null but an empty List as default "empty" value.

private List<String> getAuth(){
    return new ArrayList<>();
}

java.util.Collections.emptyList() should only be used, if you are sure that every caller of the method does not change the list (does not try to add any items), as this would fail on this unmodifiable List. Only iterating over the list would be fine.
If you can guaranty this, then the empty List is even better, as it does not create a new object all the time.

Simulant
  • 19,190
  • 8
  • 63
  • 98