我有一整套功能如下:
package rules;
import "project/some"
func frobDiscountLimit(frob some.Frob, maxDiscount float64) (RuleStatus, string)
func frobDiscountPercentageLimit(frob some.Frob, maxDiscountPercentage float64) (RuleStatus, string)
func frobUsageLimit(frob some.Frob, interval valueInterval) (RuleStatus, string)
func frobPermanentExpiryLimit(frob some.Frob) (RuleStatus, string)
func frobVoucherValidity(frob some.Frob, maxValidityDays uint) (RuleStatus, string)
用法示例:
package rules
import "project/some"
func doChecks(frob some.Frob) {
status, message := frobDiscountLimit(frob, 100)
if status != PASSED {
....
}
... evaluate all remaining rules here ...
}
我想知道它是否有任何优势:
func (f someFrob) discountLimit(maxDiscount float64) (RuleStatus, string)
...
写作似乎更短,但我不确定哪种是正确的风格。因为我不认为这些验证方法是“对象的一部分”,所以它们不是some.Frob
对象行为的一部分(不像是{{1}的属性的getter或setter。 })。
答案 0 :(得分:4)
你可以这样做,以避免必须反复明确地传递frob
,同时仍然能够避免在frob
上制作这些函数方法。
type frobChecker struct {
frob some.Frob
}
func (fc frobChecker) discountLimit(maxDiscount float64) (RuleStatus, string)
func (fc frobChecker) discountPercentageLimit(maxDiscountPercentage float64) (RuleStatus, string)
func (fc frobChecker) usageLimit(interval valueInterval) (RuleStatus, string)
func (fc frobChecker) permanentExpiryLimit() (RuleStatus, string)
func (fc frobChecker) voucherValidity(maxValidityDays uint) (RuleStatus, string)
func doChecks(frob some.Frob) {
fc := frobChcker{frob}
status, message := fc.discountLimit(100)
if status != PASSED {
....
}
... evaluate all remaining rules here ...
}