A NullPointerException in Java application is best way to solve it and that is also key to write robust programs which can work smoothly. As it said “prevention is better than cure”, same is true with nasty NullPointerException. Thankfully by applying some defensive coding techniques and following contract between multiple part of application, you can avoid NullPointerException in Java to a good extent. By the way this is the second post on NullPointerException in Javarevisited, In last post we have discussed about
common cause of NullPointerException in Java and in this tutorial, we will learn some Java coding techniques and best practices, which can be 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, you may be aware of some of these techniques and already following it in your project, but for freshers and intermediate developers, this can be good learning. By the way, if you know any other Java tips to avoid NullPointerException and reduce null checks in Java, then please share with us.
Java Tips and Best practices to avoid NullPointerException
These are simple techniques, which is very easy to follow, but has significant impact on code quality and robustness. In my experience, just first tip is 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, then you can share with us by commenting on this article.
1) Call equals() and equalsIgnoreCase() method on known String literal rather unknown object
Always call equals() method on known String which is not null. Since
equals() method is symmetric, calling a.equals(b) is 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 this call can result in NullPointerException, if caller is null.
Object unknownObject = null;
//wrong way - may cause NullPointerException
if(unknownObject.equals("knownObject")){
System.err.println("This may 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 easy Java tip or best practice to avoid NullPointerException, but results in tremendous improvement, because of equals()being a common method.
2) Prefer valueOf() over toString() where both return same result
Since calling
toString() on null object throws NullPointerException, if we can get same value by calling
valueOf() then prefer that, as passing null to valueOf() returns "null", specially in case of wrapper classes like Integer, Float, Double or BigDecimal.
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"
Follow this Java tips, if you are unsure about object being null or not.
3) Using null safe methods and libraries
There are lot of open source library out there, which does the heavy lifting of checking null for you. One of the most common one is StringUtils from Apache commons. You can use StringUtils.isBlank(), isNumeric(), isWhiteSpace() and other utility methods without worrying of NullPointerException.
//StringUtils methods are 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:
true
true
false
false
But before reaching to any conclusion don't forget to read the documentation of Null safe methods and classes. This is another Java best practices, which doesn't require much effort, but result in great improvements.
4) Avoid returning null from method, instead return empty collection or empty array.
This Java best practice or tips is 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 you make sure that basic calls like size(), length() doesn't fail with NullPointerException. Collections class provides convenient empty List, Set and Map as Collections.EMPTY_LIST, Collections.EMPTY_SET and Collections.EMPTY_MAP which can be used accordingly. Here is code example
public List getOrders(Customer customer){
List result = 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 @Nullable
While writing method you can define contracts about nullability, by declaring whether a method is null safe or not, by using annotations like @NotNull and @Nullable. Modern days compiler, IDE or tool can read this annotation and assist you to put a missing null check, or may inform you about an unnecessary null check, which is cluttering your code. IntelliJ IDE and findbugs already supports such annotation. These annotations are also part of JSR 305, but even in the absence of any tool or IDE support, this annotation itself work as documentation. By looking @NotNull and @Nullable, programmer can himself decide whether to check for null or not. By the way ,this is relatively new best practice for Java programmers and it will take some time to get adopted.
6) Avoid unnecessary autoboxing and unboxing in your code
Despite of other disadvantages like creating temporary object, autoboxing are also prone to NullPointerException, if the wrapper class object is null. For example, following code will fail with NullPointerException if person doesn't have phone number and instead return null.
Person ram = new Person("ram");
int phone = ram.getPhone();
7) Follow Contract and define reasonable default value
One of the best way to
avoid NullPointerException in Java is as simple as defining contracts and following them. Most of the NullPointerException occurs because Object is created with incomplete information or all required dependency is not provided. If you don't allow to create incomplete object and gracefully deny any such request you can prevent lots of NullPointerException down the road. Similarly if
Object is allowed to be created, than you should work with reasonable default value. for example an Employee object can not be created without id and name, but can have an optional phone number. Now if Employee doesn't have phone number than instead of returning null, return default value e.g. zero, but that choice has to be carefully taken sometime checking for null is easy rather than calling an invalid number. One same note, by defining what can be null and what can not be null, caller can make an informed decision. Choice of
failing fast or accepting null is also an important design decision you need to take and adhere consistently.
8) If you are using database for storing your domain object such as Customers, Orders etc than you should define your null-ability constraints on database itself. Since database can acquire data from multiple sources, having null-ability check in DB will ensure data integrity. Maintaining null constraints on database will also help in reducing null check in Java code. While loading objects from database you will be sure, which field can be null and which field is not null, this will minimize unnecessary != null check in code.
9) Use Null Object Pattern
This is another way of 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 have any Iterator, it can return Null object instead of null. Null object is a special object, which has different meaning in different context, for example, here an empty Iterator, calling hasNext() on which returns false, can be 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 on
Null Object pattern, where I will share few more examples of NULL objects in Java.
That’s all guys, these are couple of easy to follow Java tips and best practices to avoid NullPointerException. You would appreciate, how useful these tips can be, without too much of effort. If you are using any other tip to avoid this exception, which is not included in this list, than please share with us via comment, and I will include them here.
Read more: http://javarevisited.blogspot.com/2013/05/ava-tips-and-best-practices-to-avoid-nullpointerexception-program-application.html#ixzz41vxzXEdb
原文:http://javarevisited.blogspot.com/2013/05/ava-tips-and-best-practices-to-avoid-nullpointerexception-program-application.html
- Java – Top 5 Exception Handling Coding Practices to Avoid
This article represents top 5 coding practices related with Java exception handling that you may wan ...
- Exception (3) Java exception handling best practices
List Never swallow the exception in catch block Declare the specific checked exceptions that your me ...
- Lambda Expressions and Functional Interfaces: Tips and Best Practices
转载自https://www.baeldung.com/java-8-lambda-expressions-tips 1. Overview Now that Java 8 has reached ...
- Java 14 发布了,再也不怕 NullPointerException 了!
2020年3月17日发布,Java正式发布了JDK 14 ,目前已经可以开放下载.在JDK 14中,共有16个新特性,本文主要来介绍其中的一个特性:JEP 358: Helpful NullPoint ...
- [Java学习笔记]Java Tips
1.Java没有sizeof关键字 , volatile是java关键字.详情见:http://www.cnblogs.com/aigongsi/archive/2012/04/01/2429166. ...
- Java - Tips
001 - Java中print.printf与println的区别? printf:格式化输出,用来控制输出的格式. print:标准输出,不换行. println:标准输出,换行.例如,print ...
- PTA Java tips(转载)
在PTA提交Java程序需要注意如下几个要点 1. Main类与Scanner 1.1 Main类 你提交的所有程序都应该以如下形式出现 public class Main{ public stati ...
- 【Java Tips】boolean的类型与string类型的转换
boolean类型转化为string boolean b = true; String s = String.valueOf(b); System.out.println(s);
- Java Tips: 使用Pattern.split替代String.split
String.split方法很常用,用于切割字符串,split传入的参数是正则表达式,它的内部是每次都comiple正则表达式,再调用Pattern.split方法: public String[] ...
随机推荐
- intellij idea 13&14 插件推荐及快速上手建议 (已更新!)
原文:intellij idea 13&14 插件推荐及快速上手建议 (已更新!) 早些年 在外企的时候,公司用的是intellij idea ,当时也是从eclipse.MyEclipse转 ...
- Django查询的琐碎记录
我的需求是这样的,获取指定用户的获“赞”总数. 用户 models.py class UserProfile(models.Model): user = models.OneToOneField(Us ...
- c#之冒泡排序的三种实现和性能分析
冒泡排序算法是我们经常见到的尤其是子一些笔试题中. 下面和大家讨论c#中的冒泡排序,笔者提供了三种解决方案,并且会分析各自的性能优劣. 第一种估计大家都掌握的,使用数据交换来实现,这种就不多说了,园子 ...
- 实例学习SSIS(二)--使用迭代
原文:实例学习SSIS(二)--使用迭代 导读: 实例学习SSIS(一)--制作一个简单的ETL包 实例学习SSIS(二)--使用迭代 实例学习SSIS(三)--使用包配置 实例学习SSIS(四)-- ...
- Android仿微信气泡聊天界面设计
微信的气泡聊天是仿iPhone自带短信而设计出来的,不过感觉还不错可以尝试一下仿着微信的气泡聊天做一个Demo,给大家分享一下!效果图如下: 气泡聊天最终要的是素材,要用到9.png文件的素材,这样气 ...
- Effective C++(14) 在资源管理类中小心copying行为
问题聚焦: 上一条款所告诉我们的智能指针,只适合与在堆中的资源,而并非所有资源都是在堆中的. 这时候,我们可能需要建立自己的资源管理类,那么建立自己的资源管理类时,需要注意什么呢?. ...
- MVC应用程序请求密码的功能1
MVC应用程序请求密码的功能(一) 经过一系列的练习,实现了会员注册<MVC会员注册>http://www.cnblogs.com/insus/p/3439599.html,登录<M ...
- ruby gsub gsub! chomp chomp! 以及所有类似函数用法及区别
ruby中带“!"和不带"!"的方法的最大的区别就是带”!"的会改变调用对象本身了.比方说str.gsub(/a/, 'b'),不会改变str本身,只会返回一个 ...
- github开源项目
开源一小步,前端一大步 作为一名前端攻城狮,相信不少人已经养成了这样的习惯.当你进入一个网站,总会忍不住要打开控制台看下它是如何布局的,动画是如何实现的等.这也是前端开发者一个不错的的学习途径. ...
- IceMx.Mvc 我的js MVC 框架五、完善植物大战僵尸(雏形版增加动画)
有图有真相 说明 实在找不到僵尸的素材,从网上扒了一个山寨的僵尸,只有4张的一个连续图片,所以动作有点僵硬,植物的图片是自己处理的,非专业所以……咳咳!. 背景是自己抠下来2块儿拼接的,看在这么辛苦的 ...