我有一整套的功能看起来像这样:

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对象的行为的一部分(不同于some.Frob属性的 getter 或 setter )。

最佳答案

您可以执行类似的操作,以避免不得不一遍又一遍地显式传递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 ...
}

10-04 23:17