The control _java of Java null pointer elicited by @notnull annotation

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. Here are some Java tips to minimize the image! =null The code for this check. As an experienced Java program ape, you may be aware of these techniques used in a part of the project. But it's a good learning opportunity for college first-year students and mid-level developers.

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

1 calling equal () and equalsingnorecase () instead of unknown objects in an already string (string)

Usually in an already non-empty string is called Equals (). Because the equal () method is symmetric, calling a.equal () is equal to calling B.equal (), and that's why many of the parts notice objects A and B, if the empty side is called to cause the null pointer.

Object unknownobject = 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 common method.

2 to use valueof () instead of ToString () when both return the same result

Nullpointexception is thrown because the empty object invokes 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 such as integer,float,double or Bigdecimla.

BigDecimal BD = GetPrice ();
SYSTEM.OUT.PRINTLN (String.valueof (BD)); Doesn ' t throw NPE
System.out.println (bd.tostring ());//throws "Exception in thread" main " Java.lang.NullPointerException "

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

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

Now there are many open source components that have been checked for you for NULL. One of the most common is the stringutils of Apache. You can use Stringutils.isblank (), Isnumberic (), Iswhitespace () and other tools to worry 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:
true
true
false

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

4 Avoid returning null from a method by returning 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 a nullpointexception. The collection class can provide convenient empty list,set and maps, (these) have 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) { 
  List result = collections.empty_list; 
return result; 

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

5 using @notnull and @nullable annotations

When writing you can define the contract nullability (nullability), use a comment like @notnull and @nullable to indicate whether the method is empty (null safe). Modern compilers, Ides, and other tools can read this annotation to help you do an empty check or to tell you whether you need an empty check. Intellijide and FindBugs have supported this annotation. These comments are also part of JSR 305, a standard that can be understood as Java. By seeing @notnull and @nullable, program apes can decide for themselves whether to go for an empty check. By the way, for the Java program Ape, this is the best new practice, though it takes a little time to adapt.

6 Follow the Convention and define a reasonable default value

In the Java realm, one of the best ways to avoid null pointers is to set conventions and comply with conventions. Most nullpointexception occur 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 such requirements, you can prevent many nullpointexception that occur after a period of time. If the object is allowed to be created, then you should set a reasonable default value. For example, an employee (Employee) object may not be created without an ID and name attribute, but can have a pghone number (phone numbers) to choose from. If employee does not have phone number, then return a 0来 instead of returning a null value. However, this process must be handled with great care to check for null values rather than checking for illegal input. Also note that when you define a null value or cannot be NULL, the caller is reminded to make the informed decision. The choice or acceptance of NULL values after a failure is also an important design you need to focus on.

7 If you use a database to store your domain objects (Demain object)
For example: Customer, orders, etc., then you should define some constraints on the null values in the database. Because a database can require data from multiple sources, checking for null values in the database will ensure the integrity of the data. Keeping a constraint on null values in the database also allows you to reduce the code that reduces the empty check in Java. When you take an object out of the database, you can make sure that the attributes are empty and that the attributes are not nullable, which will minimize the code for the empty check.

8 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 is going to use some similar collection.iterator () method to return the iterator. If the caller does not have any of these methods, 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. As with these methods of returning Contrainter or conllection types, the empty objects (Empty object) should be used instead of returning null.

Related Article

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.