BMBM
BMBM

Reputation: 16013

Are methods instead of functions preferred in this case

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).

Upvotes: 0

Views: 45

Answers (1)

Chris Cherry
Chris Cherry

Reputation: 28554

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 ...
}

Upvotes: 4

Related Questions