I have a method that is given a Set of objects. A method it delegates to requires that the Set does not contain any null elements. I would like to check the precondition that the Set contains no null elements early, in the method before the delegation. The obvious code do do so is this:
public void scan(Set<PlugIn> plugIns) { if (plugIns == null) { throw new NullPointerException("plugIns"); } else if (plugIns.contains(null)) { throw new NullPointerException("plugIns null element"); } // Body } But this is incorrect, because Set.contains() may throw a NullPointerException if the Set implementation itself does not permit null elements. Catching then ignoring the NullPointerException in that case would work but would be inelegant. Is there a neat way to check this precondition?
Is there a design flaw in the Set interface? If a Set implementation may never contain a null, why not instead require Set.contains(null) to always return false? Or have a isNullElementPermitted() predicate?
Setand disallownullputs. Also, I would not use theelsehere.Set, but want to ensure it contains nonulls as per your class contract. And then if someone actually passes in aSetthat doesn't permitnulls, your safetycontainscheck throws a NPE because it is in the specification. This is design error IMHO, as there is nothing the caller can do about it (ie, no way to ask if the Set permits nulls or not), not to mention that it seems stupid to throw a NPE in this case instead of just returningfalse.