I am creating an application which retrieves images from the web. In case the image cannot be retrieved another local image should be used.
While trying to execute the f
It's probably slightly more efficient to catch a NullPointerException. The above methods mean that the runtime is checking for null pointers twice.
I use this approach:
if (null == drawable) {
//do stuff
} else {
//other things
}
This way I find improves the readability of the line - as I read quickly through a source file I can see it's a null check.
With regards to why you can't call .equals()
on an object which may be null
; if the object reference you have (namely 'drawable') is in fact null
, it doesn't point to an object on the heap. This means there's no object on the heap on which the call to equals()
can succeed.
Best of luck!
Just to give some ideas to oracle Java source developer :-)
The solution already exists in .Net and is more very more readable !
In Visual Basic .Net
Drawable drawable
= If(Common.getDrawableFromUrl(this, product.getMapPath())
,getRandomDrawable()
)
In C#
Drawable drawable
= Common.getDrawableFromUrl(this, product.getMapPath()
?? getRandomDrawable();
These solutions are powerful as Optional Java solution (default string is only evaluated if original value is null) without using lambda expression, just in adding a new operator.
Just to see quickly the difference with Java solution, I have added the 2 Java solutions
Using Optional in Java
Drawable drawable =
Optional.ofNullable(Common.getDrawableFromUrl(this, product.getMapPath()))
.orElseGet(() -> getRandomDrawable());
Using { } in Java
Drawable drawable = Common.getDrawableFromUrl(this, product.getMapPath());
if (drawable != null)
{
drawable = getRandomDrawable();
}
Personally, I like VB.Net but I prefer ?? C#
or if {}
solution in Java ... and you ?