Java – SonarQube is complaining about: “Use isEmpty() to check whether the collection is empty or not.”

code-qualitycoding-stylejavareadability

So as my the title says, SonarQube is complaining whenever you use

list.size() == 0

or

list.size > 0

However I started changing to isEmpty() and !is.Empty() and noticed the code becomes way less readable and had to change it back, therefore I don't think it's better to use the isEmpty() method as you have to read the condition very attentively instead of just seeing what the if clause does…

So I kind of totally disagree with SonarQube and my deciding argument is that using isEmpty is makes the code much less readable. Do you guys see any real advantages of using the isEmpty instead of checking the size when using this with Java collections which would outweigh the increased readability when not using it?

Best Answer

You should check the justification SonarQube gives as to why it makes the suggestion. I would bet that the primary reason is for performance, not readability.

If you don't like the readability of !collection.isEmpty(), then you could always use collection.isEmpty() == false.