Java tips and the best way to avoid NullPonintException in Java application
In a java application, a NullPonintException (null pointer exception) is the best solution (problem). At the same time, a null pointer is also the key to writing robust and smooth running code. The phrase “prevention is better than treatment” also applies to the unpleasant NullPonintException. By applying defensive coding techniques and following conventions between multiple parts, you can avoid NullPointException to a large extent. The following Java tips can minimize images! =null code for this kind of check. As an experienced java programmer, you may realize that some of these technologies are used in some projects. But for first-year college students and intermediate developers, this is a great learning opportunity.
These are some simple techniques that are easy to learn, but they are really important for code quality and robustness. In my experience, just the first trick has played a big role in improving code quality.
1) Call equal() and equalsingnoreCase() on the existing String (string) instead of unknown objects
Usually, equals() is called on the non-empty string already. Because the equal() method is symmetric, calling a.equal() is equivalent to calling b.equal(), and this is why many pay attention to objects a and b, if one side of the empty will cause a null pointer.
Object unknownObject = null;//wrong way - may cause NullPointerExceptionif(unknownObject.equals("knownObject")){ System.err.println("This may result in NullPointerException if unknownObject is null");}//right way - avoid NullPointerException even if unknownObject is nullif("knownObject".equals(unknownObject)){ System.err.println("better coding avoided NullPointerException");}This is the most important java trick to avoid NullPointException, but the result will be a huge improvement because equal() is a very common method.
2) When both return the same result, valueOf() is preferred instead of toString()
Because an empty object will throw a NullPointException when calling toString(). If we can get the same value by calling value(), we should use valueOf(). This will pass a null value. Especially in cases of packaging classes like Integer, Float, Double or BigDecimla.
BigDecimal bd = getPrice();System.out.println(String.valueOf(bd)); //doesn't throw NPESystem.out.println(bd.toString()); //throws "Exception in thread "main" java.lang.NullPointerException"
If you are not sure if the object you are using is empty, please use this JAVA trick
3) Use null safe method or class library
There are many open source components that have null checked for you now. One of the most common ones is Apache's 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:truetruefalsefalse
But don't forget to read the documentation on Null security methods and classes before making any conclusions. This is another best java drill, which won't require you to put in a lot of effort, but will make you a lot of progress.
4) Avoid returning empty collection or empty array instead of returning Null from the method
This java technique is also mentioned in Joshua Bloch's "Effective Java". This book is also a source for improving JAVA coding capabilities. By returning an empty collection or an empty array, it can be determined that basic calls like size() and length() will not throw a NullPointException. The Collection class can provide convenient empty List, Set and Map, (these) have Collections.EMPTY_LIST, Collections.EMPTY_SET and Collections.EMPTY_MAP and 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) Comment with @NotNull and @Nullable
When writing you can define a convention nullability, you should prompt whether this method is null safe by using comments like @NotNull and @Nullable. Modern compilers, IDEs and other tools can read this comment to help you do an empty check or tell you whether you need an empty check. IntelliJIDE and findbugs already support this annotation. These comments are also part of JSR 305 (Translator's Note: It can be understood as the standard of java). By seeing @NotNull and @Nullable, programmers can decide whether to do the empty check. By the way, this is the new best practice for JAVA programmers, although it takes a little time to adapt.
6) Follow the conventions and define reasonable default values
In the Java field, one of the best ways to avoid null pointers is to make agreements and abide by them. Most NullPointExceptions occur because they use incomplete information or are not provided with all dependencies to create objects. If you do not allow creating incomplete objects and negate any such requirements, you can prevent many NullPointExceptions that occur after a while. 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 the Id and Name attributes, but it can have an optional pghone number. If Employee does not have a phone number, then return a 0 instead of returning a null value. But this kind of processing must handle checking null values very carefully rather than checking for illegal input. Also note that when defining a null value or not, remind the caller to make the informed decision. Choosing or accepting null values after failure is also an important design that you need to pay attention to.
7) If you use a database to store your domain object (demain object)
For example: Customer, Orders, etc., then you should define some constraints on null values in the database. Because the database can require data from multiple sources, having a check of null values in the database will ensure the integrity of the data. Keeping constraints on null values in the database will also allow you to reduce null checking in JAVA. When you take an object from the database, you can make sure that those properties can be empty and those properties cannot be empty, which will minimize the code for those empty checks.
8) Use empty object mode
This is another way to avoid NullPointException in JAVA. If a method returns an object, which caller wants to iterate over the object, which caller needs to use some methods similar to Collection.iterator() to return iterator. If the caller does not have any of the above methods, it is possible that the empty object is returned instead of null. An empty object is a special object that has different meanings in different contexts. In cases where methods like these return Contrainter or Connection type, the empty object (Empty object) inside should be used instead of returning empty.