Why null check before instanceof?

Looking through the code, I see that very often before checking instanceof there is a check if the variable is null.

It is like this: if (variable == null || !(variable instanceof Class)) { return false; }

And it can be like this: if (!(variable instanceof Class)) { return false; }

In case the variable is null, instanceof returns false, so it also checks first if the variable is null.

In the Effective Java book we can find:

Therefore the type check will return false if null is passed in, so you don’t need a separate null check.

Example of a long line of code with null checking:

So why is the version with null checking so common in the code? Wouldn’t the code be easier to read without this check?

1 Like

to me,i find this statement direct and easy to read (variable == null || !(variable instanceof Class)) { return false; } and i can easily tell that null values were checked too,i dont know what others think on this cc @ssmusoke

Return early - A detailed example from the PHP community

1 Like

It does seem unnecessary and makes the code wordier. The only benefit is to make the null check explicit – e.g., if code were refactored at some point no longer requiring the instanceof , the implied null check could be overlooked if we don’t have a test for it.

2 Likes

In summary, should it be good practice to check null before instanceof? And in the future, in the new code, use this scheme before casting?

1 Like

@burke I think we should be happy with wordier code that is clear to the intent, basically writing code for humans rather than computers