Java Tips and best practices to avoid nullpointerexception

Source: Internet
Author: User

A NullPointerException in Java application are best-solve it and that's also key to write robust programs which can Work smoothly. As it said "prevention is better than cure", same are true with nasty nullpointerexception. Thankfully by applying some defensive coding techniques and following contract between multiple part of application, you C An avoid nullpointerexception in Java to a good extent. By the the-the-second post on NullPointerException in javarevisited, and last post we have discussed about com Mon cause of NullPointerException in Java and in this tutorial,  we would learn some Java coding techniques And best practices, which can is used to avoid nullpointerexception in Java. Following these Java tips also minimize number Of !=null check, which litter lot of Java code. As an experience Java programmer, we are aware of some of these techniques and already following it in your project, b UT for freshers and intermediate developers,This can is good learning. By the the-the-the-the-know-if-any-other Java tips-to-avoid nullpointerexception and reduce null checks in Java, then-please shar E with us.

Java Tips and best practices to avoid nullpointerexceptionThese was simple techniques, which was very easy-to-follow, but had significant impact on code quality and robustness. In my experience, just first tip was resulted in significant improvement in code quality. As I said earlier, if you know any other Java tips or best practice, which can help to reduce null check and then you can Sha Re with us-commenting on the this article.1) callequals () andequalsignorecase ()method on known String literal rather unknown objectAlways call Equals () method on known String which are not null. Since equals () method is symmetric, calling A.equals (b) are same as calling B.equals (a), and that's why many programmer don ' t pay attention on object A and B. One side effect of the can result in nullpointerexception, if caller is null.

Null//wrong way-may cause nullpointerexceptionif(Unknownobject.equals (" Knownobject ")) {   System.err.println (" This could result in NullPointerException if unknownobject is null "   //rightway-avoid nullpointerexception even if unknownobject is nullif("Knownobject ". Equals (Unknownobject)) {    System.err.println (" Better coding avoided nullpointerexception ");}


The the most easy Java tip or best practice to avoid nullpointerexception, but results in tremendous improvement, Beca Use of equals () being a common method.

2) PrefervalueOf () OvertoString ()where both return same resultSince calling toString () on null object throws NullPointerException, if we can get same value by calling ValueOf () then PR  Efer that, as passing null to VALUEOF () returns "null", specially in case of wrapper classes like Integer, Float, Double or BigDecimal.

BigDecimal bd =//doesn ' t throw NPE//throws "Exception in thread" main " Java.lang.NullPointerException "

Follow this Java tips, if is unsure about object being null or not.3) Using null safe methods and librariesThe There is lot of open source libraries out there, which does the heavy lifting of checking, and null for you. One of the most common one are stringutils from Apache Commons. You can use Stringutils.isblank (), IsNumeric (), Iswhitespace () and other utility methods without worrying of nullpointere Xception.

// StringUtils methods is null safe, they don ' t throw nullpointerexception 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:truetruefalse false


But before reaching to any conclusion don ' t forget to read the documentation of Null safe methods and classes. This was another Java best practices, which doesn ' t require much effort, but the result in great improvements.4) Avoid returning null from method, instead return empty collection or empty array.This Java best practice or tips are also mentioned by Joshua Bloch in his book effective Java which is another good source of better programming in Java. By returning empty collection or empty array to make sure that basic calls like size (), length () doesn ' t-fail with NULLPO Interexception. Collections class provides convenient empty List, Set and Map as Collections.empty_list, Collections.empty_set and Collect Ions. Empty_map which can be used accordingly. Here is code example

 Public List getorders (Customer customer) {   = collections.empty_list;    return result;}

Similarly you can use Collections.empty_set and collections.empty_map instead of returning null.5) Use of annotation@NotNull and@NullableWhile writing method can define contracts about nullability, by declaring whether a method was null safe or not, by usi ng annotations like @NotNull and @Nullable. Modern days compiler, IDE or tool can-read this annotation and assist-put a missing null check, or may inform Bout an unnecessary null check, which is cluttering your code. IntelliJ IDE and FindBugs already supports such annotation. These annotations is also part of a JSR 305, but even in the absence of any tool or IDE support, this annotation itself wo RK as documentation. By looking @NotNull and @Nullable, programmer can himself decide whether to check for null or not. By the-the-the-relatively new best practice for Java programmers and it'll take some time to get adopted.6) Avoid unnecessary autoboxing and unboxing in your codeDespite of disadvantages like creating temporary object, autoboxing is also prone to nullpointerexception, if the W Rapper Class object is null. For example, following code would fail with NullPointerException if person doesn ' t has phone number and instead return Nu ll.

New Person ("Ram"); int phone = Ram.getphone ();

Not just equality but <, > can also throw nullpointerexception if used along autoboxing and unboxing. See this article to learn more pitfalls of autoboxing and unboxing in Java.7) Follow contract and define reasonable default valueOne of the best from avoid nullpointerexception in Java  is as simple as defining contracts and following them. Most of The nullpointerexception occurs because Object was created with incomplete information or all required de Pendency is not provided. If you don't allow to create incomplete object and gracefully deny any such request you can prevent lots of nullpoint Erexception down the road. Similarly if  object is allowed to is created, than you should work with reasonable default value. For example An employee object can is created without id and name, but can has an optional p Hone number. Now IF&NBSP;EMPLOYEE&NBSP;DOESN ' t has phone number than instead of returning NULL, return default value e.g. zero, but th At choice have to being carefully taken sometime checking for null are easy rather than calling an invalid number. One same note, by defining what can is null and what can is not being null, caller can make an informed decision. Choice of failing Fast or Accepting Null is also a important design decision you need to take and adhere consistently.  8)   if your is usin g database for storing your domain object such as customers, orders etc than you should define your Null-ab ility constraints on database itself. Since database can acquire data from multiple sources, have null-ability check in DB would ensure data integrity. Maintaining NULL constraints on database would also help in reducing null Check in Java code. While loading objects from the database you'll be a sure, which field can be null and which field isn't null, this would minim Ize unnecessary! = NULL Check in code.9) Use Null Object PatternThis is another to avoiding nullpointerexcpetion in Java. If a method returns an object, on which caller, perform some operations e.g. Collection.iterator () method returns iterator , on which caller performs traversal. Suppose if a caller doesn ' t has any Iterator, it can return null object instead of NULL. Null object is a special object, which have different meaning in different context, for example, where an empty Iterator, CA Lling Hasnext () on which returns false, can is a null object. Similarly in case of method, which returnscontainer or Collection types, empty object should be used instead of returning Null. I am planning to write a separate article onNull Object Pattern, where I'll share few more examples of the NULL objects in Java. That's all guys, these is couple of easy-to-follow Java tips and best practices to avoid nullpointerexception. Would appreciate, how useful these tips can be, without too much of effort. If you were using any other tip to avoid this exception, which is not included in this list, than. Share with us via Comment, and I'll include them here.



Read more:http://javarevisited.blogspot.com/2013/05/ Ava-tips-and-best-practices-to-avoid-nullpointerexception-program-application.html#ixzz41vxzxedb

Original: http://javarevisited.blogspot.com/2013/05/ Ava-tips-and-best-practices-to-avoid-nullpointerexception-program-application.html

Java Tips and best practices to avoid nullpointerexception

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.