Summary:

Null-pointer exceptions are always encountered in real coding, and this article summarizes some personal experiences with null-pointer exceptions.

Principle:

Check early, fail early.

For example, if the intent is passed to a new target activity and this parameter is required, the onCreate method in the new target activity will throw a null pointer exception and crash the program. Instead of checking when this parameter is used, problems can be found earlier. Or, in a normal method, an argument must not be null, so we say in the first line of the method, if the argument is null, throw a null-pointer exception.

Some ways:

1. Do not use NULL in Set. 2. Do not use NULL as map key. 3. Check method 4 as soon as possible. If the value is null, do not execute or end method 4. If a required parameter is encountered, such as passing a parameter to a new target activity via an intent, and the parameter must be required, check whether the new target activity has a parameter

If (getIntent() == null) throw new NullPointerException(" missing required arguments "); if(! GetIntent ().hasextra (" Argument_name ")) throw new NullPointerException(" missing required arguments ");Copy the code

5. Check whether the string is empty

    if(TextUtils.isEmpty(str)){
        //doSometing
    }
Copy the code

6. When comparing strings with constants, place constants first, for example:

"Good". The equals (var) is better than that of the var. Equals (" good ")Copy the code

7. ToString an object, as in:

String. The valueOf (obj) is superior to the obj. ToString ()Copy the code

8. Use the @nonNULL and @nullable annotations in conjunction with AndroidStudio to help you check if you’re not checking for objects that might be NULL, or if you’re doing extra checks.

CheckNotNull instead of saying if(obj == null) throw new NullPointExcetion(); Example:

public void print2(@NonNull MyObject act) {
    checkNotNull(act);
    Log.i(TAG, "print2 " + act.name);
}
Copy the code

Extension:

What is a Guava:

The Guava project contains several core libraries that are widely relied upon by Google's Java project, such as: Collections, Caching, Primitives support, Concurrency Libraries, Common Annotations , string processing, I/O, etc. All of these tools are being used every day by Google engineers in products and services. The Guava utility class uses fast fail operations on Null valuesCopy the code

Adding a project reference

Dependencies {the compile fileTree (dir: 'libs', include: [' *. Jar']) compile "com. Google. Guava guava: 18.0"}Copy the code

Reference:

Ifeve.com/google-guav…