The study notes Guava Preconditions parametric test

In the daily development, definitely you need to check parameters in order to ensure the smooth implementation of business logic continues, such as the parameter must be greater than 0 and can not be waited in vain. Usually most of the R & D to develop habits if else, but if the parameters are more and more the amount of code does not look good.

Guava offers a range of functions and static methods for verifying whether the class constructor in line with expectations, saying that if the preconditions check fails, will throw a specific exception for the pre-conditions (preconditions). this way is more elegant the

Example: if else is way before

@RequestMapping(value = "/workbench/query/user/list", method = RequestMethod.GET)
@ResponseBody
public Result workbenchCustomerStastics(String day,String name,Integer age,Integer sex,Integer type ) {
	if(StringUtils.isBlank(day)){
		return Result.getResultError("查询条件不能为空");
	}
	if(StringUtils.isBlank(name)){
		return Result.getResultError("名称不能为空");
	}
	if(age==null||age<=0){
		return Result.getResultError("年龄校验错误,年龄必须大于0");
	}
	if(sex==null||sex!=1||sex!=0){
		return Result.getResultError("性别校验错误");
	}
	if(type==null){
		return Result.getResultError("类型不能为空");
	}
}

After using Preconditions

@RequestMapping(value = "/workbench/query/user/list", method = RequestMethod.GET)
@ResponseBody
public Result workbenchCustomerStastics(String day,String name,Integer age,Integer sex,Integer type ) {
	Preconditions.checkArgument(!StringUtils.isBlank(day),"查询条件不能为空");
	Preconditions.checkArgument(!StringUtils.isBlank(name),"名称不能 为空");
	Preconditions.checkArgument(age!=null&&age>0,"年龄校验错误,年龄必须大于0");
	Preconditions.checkArgument(!(sex==null||sex!=1||sex!=0)),"性别校验错误");
	Preconditions.checkNotNull(type,"类型不能为空");
}

Preconditions provided checkArgument, checkArgument, checkState parity mode, etc., each has a plurality of authentication method overloads, abnormality information also can be used as a placeholder, such as:


public static void checkArgument(boolean expression);
public static void checkArgument(boolean expression, @Nullable Object errorMessage);
public static void checkArgument(boolean expression,@Nullable String errorMessageTemplate,@Nullable Object... errorMessageArgs)

Parameters required for verification only Preconditions This class can be, there is also a lot of other ways, are interested in children's shoes can look at the source code, it's easy to use

Published 288 original articles · won praise 88 · views 430 000 +

Guess you like

Origin blog.csdn.net/ypp91zr/article/details/102458987