Business logic dependent on model attribute

2019-09-11 13:00发布

问题:

I have a User model that has an introduced_by attribute. Based on that attributes value, I calculate my commission differently. What would be the best, most flexible way of doing this?

Should I do a switch, or maybe put everything in a flat file? Also, should I create a Commission model?

回答1:

It's a very broad question, as there is no code and no example. However, it seems to be the perfect case of a Strategy design pattern.

What I would do, is to create a class that represents the strategy for every specific range of attribute values.

E.g

PersonalCommission
CompanyCommission
HighValueCommission
DefaultCommission

Each class has a single method, let's say calculate that you can call passing an instance of the object and that returns the value of the commission.

Wherever you need to perform the calculation, just initialize a new Commission strategy object based on the User attribute and call calculate on it.

You don't even have to use a switch, as you can initialize the class dynamically.

strategy = "#{user.introduced_by}Commission".constantize
strategy.new.compute(whatever)

Of course, that's just a very simple example you'll have to adapt to your needs.