Java – is this a good if block?
Can these comparisons always safely create nullpointer exceptions?
if( myObject == null || myObject.someMethod() == someValue ) { if( myObject == null && myObject.getAlwaysTrue() ) { } }
In addition to short circuits, are there any directions for conditional evaluation in Java that take precedence?
Update: I know MyObject Anything () throws a null pointer It's just the code I met with other programmers. I wonder if there is a safe way to compress multiple checks and null checks under a single condition I'm looking for a good rule to stick to
Solution
No, this line is not safe:
if( myObject == null && myObject.getAlwaysTrue() )
If you know that MyObject is null, you should not try to dereference it If you write this:
if( myObject != null && myObject.getAlwaysTrue() )
Then it will be safe This is because & & (and | that problem) has short circuit evaluation If you write a & & B and expression a evaluates to false, expression B will not be evaluated, so it will not throw an exception Always evaluate the left operand first