java - Iterator null collection -
it's quite common have check null before iterate when not sure collection reference null or not. sample:
collection<object> collection = ... ... if(collection != null)//troublesome for(object o : collection)
of course, know empty collection better null, in cases client code cannot control nullable collection other modules (for instance, return value 3rd party code). wrote utility method:
public static <t> iterable<t> nullableiterable(iterable<t> it){ return != null ? : collections.<t>emptyset(); }
in client code, no need check null more:
for(object o : nullableiterable(collection)) ...
do think nullableiterable()
reasonable? advice? concern? thanks!
that looks good. too. developers disagree kind of defensive programming. imagine have workflow or class not supposed return null
. means getting null
bug code hide turn null
empty collection , bug never surface.
if example writing apis not support null
collections should avoid this. if client code gives null
collection not support it, should throw illegalargumentexception
let client code know there wrong provided collection. like:
public void myapinosupportfornull(collection<object> collection){ // pre condition if(collection == null) throw new illegalargumentexception("this api not support null collections!"); //... }
Comments
Post a Comment