The reserved word assert
is used in Java to perform validations of the code at run time. You must be careful when using assert
since if an evaluation fails a Error
will be thrown (more serious than a Exception
), specifically a AssertionError
and when this happens the program, if the error is not controlled the application (or thread) will be stopped. By default, the asserts
are ignored by the JVM, you can activate them by adding the parameter -enableassertions
or -ea
. As a personal recommendation, only use assert
during debug or execution time in development environments, do not enable the evaluation of assert
s in production. Important: do not confuse the reserved word assert
with assertXyz
methods of test frameworks such as JUnit or TestNG, this last group fulfill a different functionality.
Now, about whether you should always validate whether the variable is null
or not, it's a design issue. You can do what is called defensive programming, which is to defend your code of anything that may affect it such as validating if there are variables null
and replace them with default values that will not do anything, or design your application to handle the NullPointerException
at a higher level than your method. Depending on what you do, you must choose between one or the other.
About the example code that you put in the question and based on the previous explanations, I would recommend that you use the first form, the verification of null
since your code will be protected against any error:
if (img != null )
img.setVisibility(View.GONE);