Home > Mobile >  Is there a benefit in checking isEmpty before looping?
Is there a benefit in checking isEmpty before looping?

Time:09-02

I saw the following piece of code somewhere and wondered if there was any actual benefit of checking isEmpty. There isn't right?

List<Long> someIds = ..

if (someIds != null && !someIds.isEmpty()) {
    for (Long someId : someIds) {
        // something
    }
}

CodePudding user response:

Checking if a list is empty before iterating over it is a common beginners' antipattern. It doesn't hurt, but it's not necessary. It's a sign of inexperience.

Allowing null containers is a related antipattern. It's usually a mistake to allow containers to be null. You then have to check for null, and it is confusing what the difference between a null container and an empty container is. Is the distinction meaningful? Probably not.

Finally, if a variable isn't supposed to be null it's best practice not to check for and ignore null. It's better to let the code crash with a null pointer exception. Fail loud. Go out with a bang.

With all that in mind, I would usually get rid of both if checks and simply write:

List<Long> someIds = ..

for (Long someId: someIds) {
    // something
}

CodePudding user response:

It is not necessary,I like use CollectionUtil to judge

List<Long> someIds = ..

if(CollectionUtils.isNotEmpty(someIds))){

  for (Long someId: someIds) {
    // something
  }

}

  • Related