2019年2月17日 在一本書上看到這段代碼,很好奇是什麼意思?
Assert:斷言機制:
測試代碼或者調試程序時,總會做出一些假設,斷言就是用於在代碼中捕捉這些假設。當要判斷一個方法傳入的參數時,我們就可以使用斷言。
例如:
public Order create(Cart cart, Receiver receiver, PaymentMethod paymentMethod, ShippingMethod shippingMethod,
BoxMethod boxMethod, CouponCode couponCode, boolean isInvoice) {
Assert.notNull(cart);
Assert.notEmpty(cart.getCartItems());
Assert.isTrue(cart.checkedSize()>0, "購物項選擇必須大於0");
Assert.notNull(receiver);
Assert.notNull(paymentMethod);
Assert.notNull(shippingMethod);
}
這樣可以檢測傳入的參數是否符合要求,當這些斷言方法在入參不滿足要求時就會拋出 IllegalArgumentException。
Assert.notNULL()
斷言常用的方法
notNull(Object object)
notNull(Object object, String message) 該函數的意思是傳入的object必須不能爲空。如果爲空就拋出異常。
與 notNull() 方法斷言規則相反的方法是 isNull(Object object)/isNull(Object object, String message),它要求入參一定是 null。
如果不是,則會報錯。