简介
Preconditions可以快速有效简洁的完成参数校验,避免我们在代码中写很多if语句,guava将所有检验的API都放置于Preconditions类中。
API
Preconditions类大致分为6种提供参数检验的方法
方法声明 | 描述 | 检查失败时抛出的异常 |
---|---|---|
checkArgument(boolean) | 检查boolean是否为true,用来检查传递给方法的参数。 | IllegalArgumentException |
checkNotNull(T) | 检查value是否为null,该方法直接返回value,因此可以内嵌使用checkNotNull。 | NullPointerException |
checkState(boolean) | 用来检查对象的某些状态。 | IllegalStateException |
checkElementIndex(int index, int size) | 检查index作为索引值对某个列表、字符串或数组是否有效。index>=0 && index<size *。 | IndexOutOfBoundsException |
checkPositionIndex(int index, int size) | 检查index作为位置值对某个列表、字符串或数组是否有效。index>=0 && index<=size *。 | IndexOutOfBoundsException |
checkPositionIndexes(int start, int end, int size) | 检查[start, end]表示的位置范围对某个列表、字符串或数组是否有效* | IndexOutOfBoundsException |
举例
原始写法
public User login(String userName,String password){
if(StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)){
throw new RuntimeException("用户名或密码不能为空");
}
User user = userService.queryUserByUserNameAndPassword(userName,password);
if(null == user){
throw new RuntimeException("用户名或密码错误");
}
}
我们可以这样写
public User login(String userName,String password){
Preconditions.checkArgument(!(StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)),"用户名或密码不能为空");
User user = userService.queryUserByUserNameAndPassword(userName,password);
Preconditions.checkNotNull(user,"用户名或密码错误");
}
结束语
本文章部分代码摘抄部分为凯乐君的博客