sacull
(Lukasz Debicki)
July 14, 2020, 9:07am
1
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.
Are you looking for a deeper understanding of the JavaTM programming language so that you can write code that is clearer, more correct, more robust, and more reusable? Look no further! Effective JavaTM, Second Edition, brings together seventy-eight...
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
herbert24
(Herbert Yiga)
July 14, 2020, 9:14am
2
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
ssmusoke
(Stephen Senkomago Musoke)
July 14, 2020, 11:01am
3
Return early - A detailed example from the PHP community
1 Like
burke
(Burke Mamlin)
July 14, 2020, 11:47am
4
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
sacull
(Lukasz Debicki)
July 15, 2020, 6:20am
5
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
ssmusoke
(Stephen Senkomago Musoke)
July 15, 2020, 7:13am
6
burke:
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.
@burke I think we should be happy with wordier code that is clear to the intent, basically writing code for humans rather than computers