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:

  • checkArgument throws IllegalArgumentException
  • checkState throws IllegalStateException
  • checkNotNull throws NullPointerException
  • checkElementIndex and checkPositionIndex throw IndexOutOfBoundsException, 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的更多相关文章

  1. [Google Guava] 1.2-前置条件

    原文链接 译文链接 译者: 沈义扬 前置条件:让方法调用的前置条件判断更简单. Guava在Preconditions类中提供了若干前置条件判断的实用方法,我们强烈建议在Eclipse中静态导入这些方 ...

  2. 使用 Google Guava 美化你的 Java 代码

    文章转载自:http://my.oschina.net/leejun2005/blog/172328 目录:[ - ] 1-使用 GOOGLE COLLECTIONS,GUAVA,STATIC IMP ...

  3. 【转载】使用 Google Guava 美化你的 Java 代码

    转载地址: https://blog.csdn.net/wisgood/article/details/13297535 原文地址:https://my.oschina.net/leejun2005/ ...

  4. maven命令行创建web项目报错:java.lang.NoClassDefFoundError: org/apache/commons/lang/StringUtils

    早上一上班就想新建一个web项目玩玩,没想到一敲命令创建就失败了,真是出师不利.各种折腾无果,当然我也可以用eclipse直接创建的,就是不甘心被这破问题给耍了.刚刚才发现问题原因,这个结果我也是醉了 ...

  5. Google Guava Cache 全解析

    Google guava工具类的介绍和使用https://blog.csdn.net/wwwdc1012/article/details/82228458 LoadingCache缓存使用(Loadi ...

  6. [Google Guava] 12-数学运算

    原文链接 译文链接 译者:沈义扬 范例 1 int logFloor = LongMath.log2(n, FLOOR); 2 int mustNotOverflow = IntMath.checke ...

  7. Apache Commons CLI官方文档翻译 —— 快速构建命令行启动模式

    昨天通过几个小程序以及Hangout源码学习了CLI的基本使用,今天就来尝试翻译一下CLI的官方使用手册. 下面将会通过几个部分简单的介绍CLI在应用中的使用场景. 昨天已经联系过几个基本的命令行参数 ...

  8. Apache Commons CLI命令行启动

    今天又看了下Hangout的源码,一般来说一个开源项目有好几种启动方式--比如可以从命令行启动,也可以从web端启动.今天就看看如何设计命令行启动... Apache Commons CLI Apac ...

  9. Google Guava学习笔记——简介

    Google Guava是什么东西?首先要追溯到2007年的“Google Collections Library”项目,它提供对Java 集合操作的工具类.后来Guava被进化为Java程序员开发必 ...

随机推荐

  1. oracle 11g的企业管理器

    oracle 11g的企业管理器不同于其他版本,它是B/S的,默认登录为:https://localhost:1158/em,但我试了IE8跟360浏览器都不行,谷歌浏览器是可以访问的

  2. Hashtable Dictionary List 谁效率更高

    一 前言 很少接触HashTable晚上回来简单看了看,然后做一些增加和移除的操作,就想和List 与 Dictionary比较下存数据与取数据的差距,然后便有了如下的一此测试, 当然我测的方法可能不 ...

  3. 【开源分享:入门到精通ASP.NET MVC+EF6+Bootstrap】从这里开始,一起搭框架(1)开篇介绍

    框架简介 这几年一直在做ASP.NET开发,几年前做项目都是老老实实一行行的写代码,后来发现那些高手基本都会有自己积累起来的代码库,现在称之为开发框架,基础代码不用再去堆,主要精力可以集中在业务逻辑实 ...

  4. SQL2005SP4补丁安装时错误: -2146233087 MSDTC 无法读取配置信息。。。错误代码1603的解决办法

    是在安装slq2005sp3和sp4补丁的时候碰到的问题. 起先是碰到的错误1603的问题,但网上搜索的1603的解决办法都试过了,google也用了,外文论坛也读了,依然没有能解决这个问题. 其实一 ...

  5. Pathoto项目:AWS+golang+beego搭建

    帮兄弟写了一个网站,由于要在国外使用,选择了AWS作为服务器. 不知道后面的价格如何,12个月免费的确吸引了我. 花费3天时间,从注册到服务器搭建访问,终于搞定了.下面记录一下其中容易出错的命令. 1 ...

  6. 反射 实现不同模型相同属性赋值 第二集(automapper)

    前言: 两年前写过一个 反射实现不同模型相同属性赋值 只能简单的实现两个model 相同属性名,相同类型赋值 最近又遇到这个问题,需要对相同属性名或者指定属性名 不同类型(复杂对象,如:List< ...

  7. OpenFlow

    What is OpenFlow? OpenFlow is an open standard that enables researchers to run experimental protocol ...

  8. java lambda表达式学习笔记

    lambda是函数式编程(FP,functional program),在java8中引入,而C#很早之前就有了.在java中lambda表达式是'->',在C#中是‘=>’. 杜甫说:射 ...

  9. [转]论acm与泡妞

    abstract :本文从各个方面讨论了泡妞与做题之间的相似之处与不同点,尽量的站在一个公平的角度阐述这一问题,所得的研究成果填补了国内外的理论空白. - 泡了一个好妞就好像做了一道难题一样快感都是相 ...

  10. JS 获取上一层目录

    派生到我的代码片 <script type="text/javascript"> //返回当前工作目录 function GetCurrDir(){ var pathN ...