Today I refactored a small piece of code.
Before:
$coupon_amount = self::get_coupon_prop( $coupon, 'amount' ) - $already_applied_coupons;
if ( isset( WC()->cart ) ) {
$coupon_amount = min( WC()->cart->subtotal - $already_applied_coupons, $coupon_amount );
}
if ( $coupon_amount < 0 ) {
return $discount;
}
After:
$coupon_amount = self::get_coupon_prop( $coupon, 'amount' );
if ( isset( WC()->cart ) ) {
$coupon_amount = min( WC()->cart->subtotal, $coupon_amount );
}
$coupon_amount -= $already_applied_coupons;
if ( $coupon_amount < 0 ) {
return $discount;
}
This was intuitive to me, but I wanted to prove that it really does the same thing. For that, we need to use the property .
The usual definition for min is:
Now we can use proof by cases to prove our property which will allow us to confidently refactor our code. There are two cases we can assume:
1. Case :
In this case, , and since from
we can conclude that
, then
.
So, we have that , which proves this case.
2. Case :
In this case, , and since from
we can conclude that
, then
.
So, we have that , which proves this case.
Thus, the property is proven. 🙂
There are also some other properties like and
but you can try doing these yourself. Stuff with max is proven analogously.