使用Google Guava的Preconditions进行入参校验

1、优点

在日常开发中,经常要对一些入参进行前置参数校验(比如参数不为空等),代码量不少并且复用性不高,Guava 提供的Preconditions类对入参进行统一的校验,简化我们代码中对于入参的预判断和处理,让我们入参的校验实现起来更加简单优雅。并且对不同的异常情况抛出合适类型的异常。

2、Preconditions类提供常用的校验方法如下:

方法声明(不包括额外参数) 描述 检查失败时抛出的异常
checkArgument(boolean) 检查Boolean是否为true,用来检查传递给方法的参数 IllegalArgumentException
checkNotNull(T) 检查value是否为null,该方法直接返回value,因此可以内嵌使用checkNotNull NullPointerException
checkState(boolean) 用来检查对象的某些状态 IllegalStateException
checkElementIndex(int index, int size) 检查index作为索引值对某个列表、字符串或数组是否有效。index>=0 && inde IndexOutOfBoundsException
checkPositionIndex(int index, int size) 检查index作为位置值对某个列表、字符串或数组是否有效。index>=0 IndexOutOfBoundsException
checkPositionIndexes(int start, int end, int size) 检查[start, end]表示的位置范围对某个列表、字符串或数组是否有效* IndexOutOfBoundsException

3、示例(如开发登录功能,我们需要校验前端传来的参数)

public HttpMessage loginLogin(String userName, String password){
    
    if(StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)){
        
        return new HttpMessage<>(null, HttpConstants.HttpStatus.ERROR, "用户名或密码不能为空");
    }
    User user = userService.findByUserNameAndPwd(userName,password);

    if(null == user){
        
        return new HttpMessage<>(null, HttpConstants.HttpStatus.ERROR, "用户名或密码错误");

    }

这时,我们就可以将里面的if判断去掉,使用Preconditions类提供的方法去判断

public HttpMessage loginLogin(String userName, String password){
    Preconditions.checkArgument(!(StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)),"用户名或密码不能为空");
    
    User user = userService.findByUserNameAndPwd(userName,password);
    
    Preconditions.checkNotNull(user,"用户名或密码错误");
   
    return new HttpMessage<>(user, HttpConstants.HttpStatus.OK, "请求成功");

}
是不是看着简洁优雅多了,还可以捕捉异常及错误信息,一般可以写个统一异常类捕捉(可根据不同的异常类型去获取),我这边为了简单直接用try{}捕捉

public HttpMessage loginLogin(String userName, String password){
    try {
        //失败时抛出的异常类型: IllegalArgumentException
        Preconditions.checkArgument(!(StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)),"用户名或密码不能为空");
    } catch (IllegalArgumentException e) {
        //e.getMessage()获取到的就是:用户名和密码不能为空
        return new HttpMessage<>(null, HttpConstants.HttpStatus.ERROR, e.getMessage());
    }
    User user = userService.findByUserNameAndPwd(userName,password);
    try {
        //失败时抛出的异常类型:NullPointerException
        Preconditions.checkNotNull(user,"用户名或密码错误");
        return new HttpMessage<>(null, HttpConstants.HttpStatus.OK, "请求成功");
    } catch (NullPointerException e) {
        //e.getMessage()获取到的就是:用户名或密码错误
        return new HttpMessage<>(user, HttpConstants.HttpStatus.ERROR, e.getMessage());
    }
}

注:maven项目别忘了加入Guava依赖

<dependency>

    <groupId>com.google.guava</groupId>

    <artifactId>guava</artifactId>

    <version>21.0</version>

</dependency>



猜你喜欢

转载自blog.csdn.net/qq_33914912/article/details/81000530