Skip to content

Null checks for values that can't possibly be null (Multimap.get, protocol buffer accessors) #85

Open
@cushon

Description

@cushon

Original issue created by cpovirk@google.com on 2013-02-12 at 02:49 AM


I see this from time to time:

if (multimap.get(foo) == null) { ... }

But Multimap.get always returns a collection (possibly empty), never null:

http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/collect/Multimap.html#get(K)

A quick search shows that this call appears a few dozen times in Google's codebase.

Another place that I see such null checks is with protocol buffers:

if (proto.getFoo() == null) { ... }

But proto fields aren't null; they have default values.

You could catch even more of these by looking for isNullOrEmpty calls:

if (Strings.isNullOrEmpty(proto.getFoo())) { ... }

But isNullOrEmpty is less likely to be a bug, since it will still fire (as the coder apparently expects) for a default value of "".

Are there other such methods? No doubt, but those are the two that spring to mind. I wonder whether there's an annotation that could identify them? JSR305 (covered in issue 44) has @Nonnull, but I think I've seen it mainly with parameters, and there's no documentation to say whether it's supposed to be used with return types.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions