duanou9739 2017-07-10 08:22
浏览 11
已采纳

在这种情况下首选方法而不是函数吗?

I have a whole set of functions that look like this:

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) 

Usage example:

package rules

import "project/some"

func doChecks(frob some.Frob) {
    status, message := frobDiscountLimit(frob, 100)

    if status != PASSED {
       ....
    }

    ... evaluate all remaining rules here ...
}

I wonder is there any advantage writing it like:

func (f someFrob) discountLimit(maxDiscount float64) (RuleStatus, string) 
...

It seems shorter to write, but I'm unsure which is the correct style. Because I don't think of these validation methods as "part of the object", they are not part of the behaviour of the some.Frob object (unlike, say, a getter or a setter for property of some.Frob).

  • 写回答

1条回答 默认 最新

  • dongwende1984 2017-07-10 08:32
    关注

    You could do something like this to avoid having to explicitly pass frob over and over, while still being able to avoid making those functions methods on 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 ...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 探针系统研发相关实习报告编写问题
  • ¥15 求帮生成一个lattice diamond的许可证
  • ¥15 大一前端新生求教学解答
  • ¥15 如何制作一个可以查看“网游有序列的装备词条”的软件/插件
  • ¥15 CS2打5E与完美天梯匹配会与服务器断开连接(黑框没标明具体原因)
  • ¥15 利用cst反推材料电磁参数,推出想x,y,z方向的相对介电常数与磁导率
  • ¥15 求帮助!用赛灵思FPGA XC7A35T对一个频率50MHz的数字信号读取高低电平,只用HR bank普通单端io进行采样可以吗
  • ¥15 训练准确率100%,测试准确率只有50%
  • ¥15 grafana创建dashhabord提示no data sources of type Prometheus Alert
  • ¥15 python用arima时间序列法预测不出结果 急