Google Guava vs Apache Commons for Argument Validation
It is an established good practice to validate method arguments at the beginning of the method body. For example you could check that the passed value is not negative before doing some calculation:
|
1
2
3
4
5
6
|
public int doSomeCalculation(int value) { if (value < 0) { throw new IllegalArgumentException("negative value"); } ...} |
It can be written slightly shorter using the good old Apache Commons:
Validate.isTrue(value >= 0, "negative value"); |
More recently the same behavior can be achieved with Google Guava after statically importing the Preconditions class:
checkArgument(value >= 0, "negative value"); |
At surface it looks quite similar but usually the devil is in the details so I decided to take a closer look at both approaches. In this post I’m going to describe the differences between the two libraries regarding argument validation.
Static imports
The first immediately obvious difference is that Guava requires static import to look nice.Validate.isTrue() looks better than Preconditions.checkArgument(). Personally, I don’t mind static imports in my code. For some people it might be a small disadvantage though. Especially for those who don’t know how to work with them in the IDE yet. Also, if you work on some ancient project that still uses Java earlier than 5.0 you won’t be able to use Guava at all.
Types of exceptions
All methods from Validate class in Apache Commons throw IllegalArgumentExceptionwhen validation fails. Sometimes it make sense to throw a different exception type. Guava make it possible. For example:
checkArgumentthrowsIllegalArgumentExceptioncheckStatethrowsIllegalStateExceptioncheckNotNullthrowsNullPointerExceptioncheckElementIndexandcheckPositionIndexthrowIndexOutOfBoundsException, etc.
It’s obvious from the method name what exception gets thrown. I like this clear distinction in Guava.
Message parameters
It’s a good idea to give as much information about the failure as possible. For example if you validate that a number is positive you should add the actual number in the exception message if it’s not. In the example below it is done using the string concatenation directly:
Validate.isTrue(i > 0, "Should be positive but was: " + i); |
In Commons Validate.isTrue() method you can pass additional parameter instead. It offers a performance benefit because the string concatenation is actually done only when the validation fails.
Validate.isTrue(i > 0, "Should be positive but was: ", i); |
You can do a similar thing in Guava:
checkArgument(i > 0, "Should be positive but was: %s", i); |
Additionally, Guava uses varargs for message parameters and you could also write:
checkArgument(i > MIN, "Expected more than %s, got %s", MIN, i); |
In this case it’s also more readable than using string concatenation:
checkArgument(i > MIN, "Expected more than " + MIN + ", got " + i); |
Validating collections and arrays
Apache Commons has some additional validations for collection and arrays that you won’t find in Guava:
allElementsOfType(Collection collection, Class clazz)Validate.notEmpty(Collection collection)Validate.notEmpty(Map map)Validate.notEmpty(Object[] array)Validate.noNullElements(Collection collection)Validate.noNullElements(Object[] array)
This first one might be handy in legacy project not using generics. Others are generally useful.
On the other hand you can combine Guava Preconditions with any utility methods. In the example below I use the isNotEmpty method from Commons CollectionUtils in conjunction with Guava Preconditions to ensure that the list is not null and not empty:
checkArgument(isNotEmpty(list)); |
Assignment after validation
It’s common to assign a method argument to a field after validation. For example withValidate from Apache Commons you could write:
|
1
2
3
4
|
public Class(Object parameter) { Validate.notNull(parameter); this.field = parameter;} |
The checkNotNull from Guava Preconditions returns the validated reference. This allows validation and assignment in one line:
|
1
2
3
|
public Class(Object parameter) { this.field = checkNotNull(parameter);} |
Summary
In summary, here are the main advantages of both classes:
Apache Commons Validate
- Works in old versions of Java
- Readable without static imports
- Collection and array validations
Google Guava Preconditions
- Additional exception types
- Better handling of message arguments
- Easy assignment after not null check
Verdict
I prefer Guava Preconditions over Commons Validate for argument validation.
Google Guava vs Apache Commons for Argument Validation的更多相关文章
- [Google Guava] 1.2-前置条件
原文链接 译文链接 译者: 沈义扬 前置条件:让方法调用的前置条件判断更简单. Guava在Preconditions类中提供了若干前置条件判断的实用方法,我们强烈建议在Eclipse中静态导入这些方 ...
- 使用 Google Guava 美化你的 Java 代码
文章转载自:http://my.oschina.net/leejun2005/blog/172328 目录:[ - ] 1-使用 GOOGLE COLLECTIONS,GUAVA,STATIC IMP ...
- 【转载】使用 Google Guava 美化你的 Java 代码
转载地址: https://blog.csdn.net/wisgood/article/details/13297535 原文地址:https://my.oschina.net/leejun2005/ ...
- maven命令行创建web项目报错:java.lang.NoClassDefFoundError: org/apache/commons/lang/StringUtils
早上一上班就想新建一个web项目玩玩,没想到一敲命令创建就失败了,真是出师不利.各种折腾无果,当然我也可以用eclipse直接创建的,就是不甘心被这破问题给耍了.刚刚才发现问题原因,这个结果我也是醉了 ...
- Google Guava Cache 全解析
Google guava工具类的介绍和使用https://blog.csdn.net/wwwdc1012/article/details/82228458 LoadingCache缓存使用(Loadi ...
- [Google Guava] 12-数学运算
原文链接 译文链接 译者:沈义扬 范例 1 int logFloor = LongMath.log2(n, FLOOR); 2 int mustNotOverflow = IntMath.checke ...
- Apache Commons CLI官方文档翻译 —— 快速构建命令行启动模式
昨天通过几个小程序以及Hangout源码学习了CLI的基本使用,今天就来尝试翻译一下CLI的官方使用手册. 下面将会通过几个部分简单的介绍CLI在应用中的使用场景. 昨天已经联系过几个基本的命令行参数 ...
- Apache Commons CLI命令行启动
今天又看了下Hangout的源码,一般来说一个开源项目有好几种启动方式--比如可以从命令行启动,也可以从web端启动.今天就看看如何设计命令行启动... Apache Commons CLI Apac ...
- Google Guava学习笔记——简介
Google Guava是什么东西?首先要追溯到2007年的“Google Collections Library”项目,它提供对Java 集合操作的工具类.后来Guava被进化为Java程序员开发必 ...
随机推荐
- crontab小结
crontab是linux下的计划任务,可以用来定时或者按计划运行命令. 创建计划任务: 1.使用crontab -e命令,直接创建计划任务 2.使用编辑器编写好计划任务的文件后,再使用crontab ...
- springmvc集成shiro登录失败处理
一般的登录流程会有:用户名不存在,密码错误,验证码错误等.. 在集成shiro后,应用程序的外部访问权限以及访问控制交给了shiro来管理. shiro提供了两个主要功能:认证(Authenticat ...
- ubuntu-12.10-server中打开终端的方式
ubuntu-12.10-server系统在图形界面的任务栏上找不到终端的踪影,可以使用以下两种方式调出 1.在图形界面中点击Dash Home 点击后搜索terminal即可 2.可以通过快捷键CT ...
- ASP.NET 系列:单元测试之SmtpClient
使用SmtpClient发送Email时,我们可以创建ISmtpClient接口和SmtpClientWrapper适配类,在单元测试中对ISmtpClient进行Mock或自定义FackeSmtpC ...
- [BZOJ1116][Poi2008]LCO(并查集)
题目:http://hzwer.com/3010.html 分析:注意这里无向边是对入度没有贡献的. 那么对于一个n个点的连通块而言,如果它是一颗树(n-1条边),那么把所有边全部从某个根开始向下指, ...
- WinForm 问题集锦
[1]重用项目窗体解决方案: 1. 把FmMain.cs 和 FmMain.Designer.cs 和 FmMain .resx 三个文件复制到程序目录下: 2. 在vs里面添加现有项, 选择FmMa ...
- java中的集合和数组
数组Array和集合的区别: (1)数组是大小固定的,并且同一个数组只能存放类型一样的数据(基本类型/引用类型) (2)JAVA集合可以存储和操作数目不固定的一组数据. (3)若程序时不知道究竟需要多 ...
- android 使用多个接口
今天,好久没有这么用过都忘记可以这样用了.来记录下: 一个类想要使用多个接口可以implements 接口1 , 接口2,...
- java虚拟机和Dalvik虚拟机的区别
java虚拟机和Dalvik虚拟机的区别: java虚拟机Dalvik虚拟机 java虚拟机基于栈. 基于栈的机器必须使用指令来载入和操作栈上数据,所需指令更多更多dalvik虚拟机是基于寄存器的 j ...
- Myeclipse下JSP打开报空指针异常解决方法。
Myeclipse下JSP打开报空指针异常解决方法 一.运行JSP文件就出错 静态的JSP页面访问时候正常,只要是牵涉到数据库的页面就出错,出错见下图. 出现这种情况让我调试了一天,各种断点,各种改代 ...