Best practice to validate null and empty collection in Java

后端 未结 9 2039
北海茫月
北海茫月 2020-12-12 10:57

I want to verify whether a collection is empty and null. Could anyone please let me know the best practice.

Currently, I am checking as below:



        
9条回答
  •  星月不相逢
    2020-12-12 11:24

    If you need to check for null, that is the way. However, if you have control on this, just return empty collection, whenever you can, and check only for empty later on.

    This thread is about the same thing with C#, but the principles applies equally well to java. Like mentioned there, null should be returned only if

    • null might mean something more specific;
    • your API (contract) might force you to return null.

提交回复
热议问题