【Guava】开发过程中,业务逻辑优雅的参数校验 Preconditions
原文 文章
描述
在开发过程中,对数据格式或者数据在业务上的期望值验证是必须要做的, 这样可以进一步保证方法能够按照正常流程执行下去, 而不是完全通过错误处理来保证流程正确执行,毕竟错误处理是比较消耗资源的方式。
但是常规if...else...写法既有大量代码量, 又会导致读起来非常不友好,且复用性不高。
if(age>0&&neme!=null&&neme.isEmpty()!=true){
System.out.println("a person age:"+age+",neme:"+neme);
}else{
System.out.println("参数输入有误!");
}
Guava Preconditions
1 .checkArgument(boolean) :
功能描述:检查boolean是否为真。 用作方法中检查参数
失败时抛出的异常类型: IllegalArgumentException
example
@Test
public void testCheckArgument(){
DemoVO demoVO = DemoVO.builder()
.age(1L)
.name("demo bane")
.history(Arrays.asList("a", "b", "c"))
.build();
// 非空对象校验
Preconditions.checkArgument(demoVO != null, "入参非法!");
// 空对象校验
try {
Preconditions.checkArgument(null != null, "入参非法!");
}catch (IllegalArgumentException e){
Assert.assertEquals(e.getMessage(), "入参非法!");
}
Preconditions.checkArgument(StringUtils.isNotEmpty(demoVO.getName()), "name为空!");
}
2.checkNotNull(T):
功能描述:检查value不为null, 直接返回value;
失败时抛出的异常类型:NullPointerExceptionexample
@Test
public void testCheckNotNull(){
Preconditions.checkNotNull("", "name为null");
Preconditions.checkNotNull("a", "name为null");
try {
Preconditions.checkNotNull(null, "name为null");
}catch (NullPointerException e){
Assert.assertEquals(e.getMessage(), "name为null");
}
}
3.checkState(boolean):
功能描述:检查对象的一些状态,不依赖方法参数。 例如, Iterator可以用来next是否在remove之前被调用。
失败时抛出的异常类型:IllegalStateException
@Test
public void testCheckState(){
DemoVO demoVO = DemoVO.builder()
.age(1L)
.name("demo bane")
.history(Arrays.asList("a", "b", "c"))
.build();
// 表达式为true不抛异常
Preconditions.checkState(demoVO.getHistory().size() < 5, "list size 不能大于"+5);
try {
Preconditions.checkState(Arrays.asList("a", "b", "c", "a", "b", "c").size() < 5, "list size 不能大于"+5);
}catch (IllegalStateException e){
Assert.assertEquals(e.getMessage(), "list size 不能大于5");
}
}
4.checkElementIndex(int index, int size):
功能描述:检查index是否为在一个长度为size的list, string或array合法的范围。 index的范围区间是[0, size)(包含0不包含size)。无需直接传入list, string或array, 只需传入大小。返回index。
失败时抛出的异常类型:IndexOutOfBoundsException
5.checkPositionIndex(int index, int size):
功能描述:检查位置index是否为在一个长度为size的list, string或array合法的范围。 index的范围区间是[0, size)(包含0不包含size)。无需直接传入list, string或array, 只需传入大小。返回index。
失败时抛出的异常类型:IndexOutOfBoundsException
官方文档描述:
The method checkPositionIndex checks that an index passed as an argument to this method is a valid index in a list, string or array of a specified size. A position index may range from 0 inclusive to size inclusive. You don't pass the list, string or array directly, you just pass its size.
This method throws an IndexOutOfBoundsException if the index passed is not between 0 and the size given, else it returns the index value.
@Test
public void testCheckPositionIndex(){
DemoVO demoVO = DemoVO.builder()
.age(1L)
.name("demo bane")
.history(Arrays.asList("a", "b", "c"))
.build();
int size = demoVO.getHistory().size();
System.out.println("size:" + size);
int index = 0;
Preconditions.checkPositionIndex(index, size - 1, "index: " + index + " 不在 list中, List size为:" + size);
index = 1;
Preconditions.checkPositionIndex(index, size - 1, "index: " + index + " 不在 list中, List size为:" + size);
index = 2;
Preconditions.checkPositionIndex(index, size - 1, "index: " + index + " 不在 list中, List size为:" + size);
try {
index = 3;
Preconditions.checkPositionIndex(index, size - 1, "index: " + index + " 不在 list中, List size为:" + size + ".");
}catch (IndexOutOfBoundsException e){
Assert.assertEquals(e.getMessage(), "index: 3 不在 list中, List size为:3. (3) must not be greater than size (2)");
}
try {
index = 4;
Preconditions.checkPositionIndex(index, size - 1, "index: " + index + " 不在 list中, List size为:" + size + ".");
}catch (IndexOutOfBoundsException e){
Assert.assertEquals(e.getMessage(), "index: 4 不在 list中, List size为:3. (4) must not be greater than size (2)");
}
}
@Test
public void givenArrayAndMsg_whenCheckPositionEvalsFalse_throwsException() {
int[] numbers = { 1, 2, 3, 4, 5 };
String message = "Please check the bound of an array and retry";
assertThatThrownBy(
() -> Preconditions.checkPositionIndex(6, numbers.length - 1, message))
.isInstanceOf(IndexOutOfBoundsException.class)
.hasMessageStartingWith(message).hasNoCause();
}
6.checkPositionIndexes(int start, int end, int size):
功能描述:检查[start, end)是一个长度为size的list, string或array合法的范围子集。伴随着错误信息。
失败时抛出的异常类型:IndexOutOfBoundsException