Java null pointer exception solution collection (reproduced) (Exception in thread "main" java.lang.NullPointerException)

1) Call equals() and equalsIgnoreCase() methods from known String objects instead of unknown objects.

Always call the equals() method from a known non-empty String object. Because the equals() method is symmetric, calling a.equals(b) and calling b.equals(a) are exactly the same, which is why programmers are so careless about objects a and b. If the caller is a null pointer, this call may cause a null pointer exception

 Object unknownObject = null;
//错误方式 – 可能导致 NullPointerException
if (unknownObject.equals("knownObject")) {
        System.err.println("This may result in NullPointerException if unknownObject is 
        null");
}
//正确方式 - 即便 unknownObject是null也能避免NullPointerException
if ("knownObject".equals(unknownObject)) {
        System.err.println("better coding avoided NullPointerException");
}


This is the simplest Java technique to avoid null pointer exceptions, but it can lead to huge improvements because equals() is a common method.

2) When valueOf() and toString() return the same result, I would rather use the former.

Because calling toString() of a null object will throw a null pointer exception, if we can use valueOf() to get the same value, we would rather use valueOf(), passing a null to valueOf() will return "null", especially In those packaging classes, like Integer, Float, Double and BigDecimal.

BigDecimal bd = getPrice();
System.out.println(String.valueOf(bd)); //不会抛出空指针异常
System.out.println(bd.toString()); //抛出 "Exception in thread "main" java.lang.NullPointerException"


3) Use null-safe methods and libraries. There are many open source libraries that have done heavy null pointer checking for you. One of the most commonly used is StringUtils in Apache commons. You can use StringUtils.isBlank(), isNumeric(), isWhiteSpace() and other tool methods without worrying about null pointer exceptions.

//StringUtils方法是空指针安全的,他们不会抛出空指针异常
System.out.println(StringUtils.isEmpty(null));
System.out.println(StringUtils.isBlank(null));
System.out.println(StringUtils.isNumeric(null));
System.out.println(StringUtils.isAllUpperCase(null));
 
Output:
true
true
false
false


 
But before making a conclusion, don't forget to read the documentation of the class for the null pointer method. This is another Java best practice that can be greatly improved without much effort.

4) Avoid returning a null pointer from the method, but return an empty collection or an empty array.

This Java best practice or technique is mentioned by Joshua Bloch in his book Effective Java. This is another technique that can better use Java programming. By returning an empty collection or an empty array, you can ensure that calls such as size(), length() will not crash due to a null pointer exception. The Collections class provides convenient empty List, Set and Map: Collections.EMPTY_LIST, Collections.EMPTY_SET, Collections.EMPTY_MAP. Here is an example.

public List getOrders(Customer customer){
List result = Collections.EMPTY_LIST;
return result;
}


You can also use Collections.EMPTY_SET and Collections.EMPTY_MAP instead of null pointers.

5) Use annotation@NotNull and @Nullable

You can define whether it can be a null pointer when writing a program. Declare whether a method is null pointer safe by using annotations like @NotNull and @Nullable. Modern compilers, IDEs or tools can read this annotation and help you add forgotten null pointer checks, or prompt you with unnecessary messy null pointer checks. IntelliJ and findbugs already support these annotations. These annotations are also part of JSR 305, but even if they are not in the IDE or tool, the annotation itself can be used as a document. Seeing @NotNull and @Nullable, programmers can decide whether to check for null pointers. By the way, this technique is relatively new to Java programmers and it will take some time to adopt it.

6) Avoid unnecessary automatic packaging and automatic unpacking in your code.

Regardless of other shortcomings such as creating temporary objects, if the wrapper class object is null, automatic wrapping is also prone to cause a null pointer exception. For example, if the person object does not have a phone number, it will return null. The following code will crash due to a null pointer exception.

Person ram = new Person("ram");
int phone = ram.getPhone();


When using automatic packaging and automatic unpacking, not only the equal sign, but also a null pointer exception will be thrown. You can learn more about the pitfalls of automatic packaging and unpacking in Java through this article.

7) Follow Contract and define reasonable default values.

One of the best ways to avoid null pointer exceptions in Java is to simply define contracts and follow them. Most null pointer exceptions occur because the object is created with incomplete information or not all dependencies are provided. If you do not allow the creation of incomplete objects and gracefully reject these requests, you can prevent a large number of null pointer exceptions in subsequent workers. Similarly, if objects are allowed to be created, you need to define a reasonable default value for them. For example, an Employee object cannot be created without an id and name, but whether it has a phone number is optional. Now if the Employee does not have a phone number, you can return a default value (such as 0) instead of returning null. But you must choose carefully. Sometimes it is more convenient to check for a null pointer than to call an invalid number. Similarly, by defining what can be null and what cannot be null, the caller can make an informed decision. Failing fast or accepting null is also an important design decision that you need to choose and implement

8) Define whether the field in the database can be empty.

If you are using a database to store your domain name objects, such as Customers, Orders, etc., you need to define the null constraint in the database itself. Because the database will get data from a lot of code, there is a check to see if the database is empty to ensure that your data is healthy. Maintaining null constraints in the data space can also help you reduce null pointer checks in Java code. When loading an object from the database, you will be clear about which fields can be null and which cannot. This can minimize unnecessary != null checks in your code.

9) Use Null Object Pattern

There is another way to avoid the null pointer exception in Java. If a method returns an object, perform some operations in the caller, for example, the Collection.iterator() method returns an iterator, and the caller performs traversal. Assume that if a caller does not have any iterators, it can return a Null object instead of null. The empty object is a special object, which has different meanings in different contexts. For example, an empty iterator can be an empty object when calling hasNext() returns false. Similarly, in the examples of methods returning Container and Collection types, empty objects can be used instead of null as the return value. I plan to write another article on the empty object pattern and share some examples of Java empty objects.

Guess you like

Origin blog.csdn.net/qq_36766417/article/details/105988180