1. 程式人生 > >Guava學習之Preconditions

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;
	}

}