Skip to content

Collection Size Or Array Length

Use proper condition to check size of Collection or length of Array

What does this mean ?

The size of a collection and the length of an array are always greater than or equal to zero. So, you should use proper condition to check size of Collection or length of Array.

What can happen ?

So testing that a size or length is greater than or equal to zero doesn't make sense, since the result is always true. Similarly testing that it is less than zero will always return false.

Sample Code

Vulnerable :

if(collection.Count >= 0){...}

if(enumerable.Count() < 0){...}

if(array.Length >= 0){...}

bool result = array.Length >=0;

Non Vulnerable :

if (list.Any()) { ... }

if (list.Count > 0) { ... }

if (array.Length >= 42) { ... }

Vulnerable :

if (myList.size() >= 0) { ... }

if (myList.size() < 0) { ... }

boolean result = myArray.length >= 0;

if (0 > myArray.length) { ... }

Non Vulnerable :

if (!myList.isEmpty()) { ... }

if (myArray.length >= 42) { ... }

References