java Method summary to avoid NullPointerException (null pointer)

  • 2020-11-03 22:12:29
  • OfStack

java Method summary to avoid NullPointerException (null pointer)

Null pointer exceptions thrown in Java applications are the best way to resolve null Pointers and are the key to writing robust programs that work well. The old saying "prevention is better than cure" is also true for such a nasty nullpointer anomaly. The good news is that by using 1 defensive coding technique to track the connections between multiple parts of your application, you can keep the null pointer exception in Java to a good level. By the way, this is the second nullpointer exception on Javarevisited. In the last post we discussed the common causes of null pointer exceptions in Java, and in this tutorial we will learn some Java programming tips and best practices. These tips will help you avoid null-pointer exceptions in Java. Following these tips also reduces the number of non-null checks that are ubiquitous in Java code. As an experienced Java programmer, you probably already know part 1 of these techniques and apply them to your projects. But for beginners and intermediate developers, it will be well worth learning. By the way, if you know of any other Java tips for avoiding null pointer exceptions and reducing null pointer checking, please share them with us.

These are simple techniques that are easy to apply, but have a significant impact on code quality and robustness. In my experience, only the first tip can significantly improve code quality. As I said earlier, if you know of any Java tips for avoiding null-pointer exceptions and reducing null-pointer checking, you can share them by commenting on this article.

1) Call the equals() and equalsIgnoreCase() methods from a known String object instead of an unknown object.

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 with the objects a and b. If the caller is a null pointer, this call may result in a null pointer exception


Object unknownObject = null;

// Wrong way   �   May lead to  NullPointerException
if(unknownObject.equals("knownObject")){
  System.err.println("This may result in NullPointerException if unknownObject is null");
}

// Right way  -  Even if the  unknownObject is null Can also avoid the NullPointerException
if("knownObject".equals(unknownObject)){
  System.err.println("better coding avoided NullPointerException");
}

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

2) Prefer valueOf() when valueOf() and toString() return the same result.

Since calling toString() on the null object would throw a null pointer exception, we would rather use valueOf() if we could get the same value using valueOf(), passing one null to valueOf() would return "null", especially in those wrapper classes like Integer, Float, Double, and BigDecimal.


BigDecimal bd = getPrice();
System.out.println(String.valueOf(bd)); // Null pointer exceptions are not thrown 
System.out.println(bd.toString()); // throw  "Exception in thread "main" java.lang.NullPointerException"

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


//StringUtils Methods are null-pointer safe; they do not throw null-pointer exceptions 
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 you make any conclusions, don't forget to read the documentation for the classes of null-pointer methods. This is another Java best practice that can be greatly improved without a lot of effort.

4) Avoid returning null Pointers from methods and instead return empty collection or empty arrays.

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


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

You can also use Collections.EMPTY_ES104en and Collections.EMPTY_ES107en instead of null Pointers.

5) Use annotation @ES111en and @ES112en

You can define null Pointers when you write a program. Declare whether a method is null pointer safe by using annotation such as @NotNull and @Nullable. Modern compilers, IDE, or tools can read this annotation and add forgotten null pointer checks for you, or tip you off to an unnecessary mess of 78 bad null pointer checks. IntelliJ and findbugs already support these annotation. These annotation are also part 1 of JSR 305, but even if they are not in IDE or the tool, the annotation itself can serve as a document. When you see @NotNull and @Nullable, the programmer can decide for himself whether to null pointer check. By the way, this technique is relatively new to Java programmers and takes a while to adopt.

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

Regardless of other disadvantages such as creating temporary objects, if the wrapper class object is null, automatic wrapping can also easily lead to null-pointer exceptions. For example, null is returned if the person object does not have a phone number, and the following code crashes because of a null pointer exception.


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

When you use automatic packaging and automatic unpackaging, it's not just the equals sign, < > Null pointer exception is also thrown. You can learn more about the pitfalls of automatic packaging and unpacking in Java in this article.

7) Comply with Contract and define reasonable defaults.

One of the best ways to avoid nullpointer exceptions in Java is to simply define contract and follow them. Most null-pointer exceptions occur because the object is created with incomplete information or because all dependencies are not provided. If you are not allowed to create incomplete objects and gracefully reject these requests, you can prevent a large number of null-pointer exceptions in the following worker. 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 id and name, but having a phone number is optional. Now if Employee does not have a phone number, you can return a default value (such as 0) instead of returning null. But you have to be careful, because sometimes checking for null Pointers is more convenient than calling invalid Numbers. Similarly, by defining what is null and what is not null, the caller can make an informed decision. failing fast or accepting null is also an important design decision that you need to make and implement

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

If you are using a database to hold your domain objects, such as Customers, Orders, etc., you need to define a constraint on whether the database itself is empty or not. Because the database takes data from a lot of code, there are checks in the database to make sure your data is healthy. Maintaining the null constraint in data air can also help you reduce null pointer checking in Java code. When loading an object from the database you will specify which fields can be null and which cannot, which can make your code unnecessary! = null check minimization.

9) Use the empty object schema (Null Object Pattern)

There is also a way to avoid null-pointer exceptions in Java. If 1 method returns an object, perform 1 operation in the caller, such as the Collection.iterator () method returns an iterator whose caller performs the traversal. Suppose that if a caller does not have any iterators, it can return an empty object (Null object) instead of null. An empty object is a special object that has different meanings in different contexts. For example, when an empty iterator calls hasNext() to return false, it could be an empty object. Similarly, in the case of returning Container and Collection methods, an empty object can be used instead of null as the return value. I'm going to write another article about the empty object pattern and share a few examples of Java empty objects.

That's it, these are a few easy-to-follow Java tips and best practices for avoiding null pointer exceptions. You can appreciate that these techniques will be very useful and not too difficult to implement. If you have other tips for this exception that are not included here, please share them with us in the comments, which I will include here.

If you have any questions, please leave a message or go to this site community exchange discussion, thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: