Guava学习之Preconditions

下面的代码,比较了使用Preconditions工具类和不使用的情况,实现同样的功能。

可以看出,前者在异常验证这块,精简了很多代码。

//import com.google.common.base.Preconditions;

public class Sum {
	public static Double sum(Double a, Double b) {
		
		//Preconditions.checkNotNull(a, "Illegal Argument passed: First parameter is Null.");
		if (a == null) {
			throw new NullPointerException("Illegal Argument passed: First parameter is Null.");
		}
		
		//Preconditions.checkNotNull(b, "Illegal Argument passed: Second parameter is Null.");
		if (b == null) {
			throw new NullPointerException("Illegal Argument passed: Second parameter is Null.");
		}
		
		//Preconditions.checkArgument(a > 0, "Illegal Argument passed: Non-positive value %s.", a);
		//Preconditions.checkArgument(b > 0, "Illegal Argument passed: Non-positive value %s.", b);
		Double d = null;

		if (a <= 0) {
			d = a;
		} else if (b <= 0) {
			d = b;
		}

		if (d != null) {
			throw new IllegalArgumentException("Illegal Argument passed: Non-positive value " + d + ".");
		}

		return a + b;
	}

}

猜你喜欢

转载自blog.csdn.net/esir82/article/details/79488311