Control of Java NULL pointers from @notnull annotations (RPM)

Source: Internet
Author: User

Java tips and best practices for avoiding nullponintexception in Java applications

In a Java application, a nullponintexception (null pointer exception) is the best way to solve (a problem). At the same time, null pointers are key to writing robust, smooth-running code. The phrase "prevention is better than cure" also applies to unpleasant nullponintexception. By applying defensive coding techniques and complying with the conventions of multiple parts, you can avoid nullpointexception to a large extent. The following Java tips can be minimized like! =null The code for this check. As an experienced Java program Ape, you may realize that some of these techniques are used in certain projects. But for first-year students and mid-level developers, this is a good learning opportunity.

This is a simple technique that's easy to learn, but it's really important for code quality and robustness. In my experience, the first little trick has been a big part of improving the quality of the code.

1) call equal () and equalsingnorecase () in the already string (string) instead of the unknown object

Normally in an already non-empty string, the Equals () is called. Because the equal () method is symmetric, calling a.equal () is equivalent to calling B.equal (), and this is why many of the ministries note objects A and B, if the empty side is called to cause a null pointer.

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

This is the most important Java technique to avoid nullpointexception, but the result will be a great improvement, because equal () is a very common method.

2) prefer to use valueof () rather than ToString () when both return the same result

Nullpointexception is thrown when an empty object calls ToString (). If we can get the same value by calling value (), we should use valueof (). This will pass a null value. Especially in the case of packaging classes like integer,float,double or Bigdecimla.

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


If you are not sure if the object you are using is empty, use this Java technique

3) Use an empty security method (Null safe) or class library

Now there are a lot of open source components that have already done a null check for you. One of the most common is the Apache stringutils. You can use Stringutils.isblank (), Isnumberic (), Iswhitespace () and other tools without worrying about nullpointexception methods.

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:truetrue false false

But before you make any conclusions, don't forget to read the documentation about null security methods and classes. This is another Java best practice, which does not require a lot of effort, but it can make a big progress for you.

4) Avoid returning null from a method in place of an empty collection or an empty array

This Java technique is also mentioned in Joshua Bloch's "effective Java". This book is also a source of improved Java coding capabilities. By returning an empty collection or an empty array you can determine that a call like size (), length () does not throw nullpointexception. The collection class is able to provide convenient empty list,set and maps, with Collections.empty_list, Collections.empty_set and Collections.empty_ Map these can be used (static variables).

The code is as follows;

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

Similarly, you can use Collections.empty_list, Collections.empty_set, and Collections.empty_map instead of returning null.

5) Use @notnull and @nullable annotations

When writing you can define about the contract nullability (nullability), to indicate whether this method is null safe by using a comment similar to @notnull and @nullable (null safe). Modern compilers, Ides, and other tools can read this comment to help you with an empty check or to tell you if you need an empty check. Intellijide and FindBugs have supported such annotations. These annotations are also part of the JSR 305 (translator's note: A standard that can be understood as Java). By seeing @notnull and @nullable, the program apes can decide for themselves whether or not to go for an empty check. By the way, for the Java program Ape, this is the best new practice, although it takes a little time to adapt.

7) Follow the conventions and define a reasonable default value

In the Java world, one of the best ways to avoid null pointers is to define conventions and to abide by the conventions. Most of the nullpointexception occurs because an incomplete message is used or is not provided with all the dependency information to create the object. If you do not allow the creation of incomplete objects and negate any of these requirements, you can prevent nullpointexception that occur after a lot of time. If the object is allowed to be created, then you should set a reasonable default value. For example, an employee object cannot be created without an ID and a name attribute, but there can be an optional Pghone number (tel). If the employee does not have a phone number, it returns a null value instead of returning a single. However, this processing must be handled with great care to check for null values instead of checking for illegal input. It is also important to note that the definition can make null values or not NULL values, reminding the caller to make informed decisions. Choosing or accepting null values after a failure is also an important design that you need to focus on.

8) If you use a database to store your domain objects (Demain object), such as: Customer, Orders, and so on, you should define some constraints on null values in the database. Because the database can require data from multiple sources, having a check of the null value in the database will ensure the integrity of the data. Keeping the constraints on null values in the database also allows you to reduce the code that reduces null checks in Java. When an object is fetched from the database, you can ensure that those properties can be empty and those properties cannot be empty, which will minimize the code for those empty checks.

9) Use empty object mode

This is another way to avoid nullpointexception in Java. If a method returns an object, which caller is going to traverse the object, which caller will use something like Collection.iterator () to return to iterator. If the caller does not have any of these methods above, then it is possible to return an empty object instead of NULL (NULL). An empty object is a special object that has different meanings in different contexts. In the case of methods such as those that return Contrainter or conllection types, the empty objects inside (empty object) should be used instead of returning empty.

Control of Java NULL pointers from @notnull annotations (RPM)

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.