Hi All,

I have a project I am going to be starting shortly, just recieved the specs. I plan on using python with flask for this project and the question I have (for now) just has to do with the python. My question is, this calculator is going to calculate ~4 different prices using different formulas, parameters, etc., should I break each calculation into its own class or does it make more sense to have one "calc" class with functions for each type of calculation? Thanks

Well it depends obviously.
I think first you have to be clear about
1. how is decided which calculation to use
2. Should it be easy to implement new calculation types, modify olders
3. How many of the parameters are and will be shared between the current and the future calculation types.
4. Are the calculations dependent on eachother

For example
price 1 based on age, registration date, baseprice, valid if the user registered more than 1 year
price 2 based on cumulated buys, valid if the user have bought more than 200$
price 3 based on minimum of price 1 and price 2, valid if price1 and price2 is valid.

If that is the first set of requirenment, than I would say something like:

class Calculation:
    def __init__(parameters needed to decide, userid, registrationlen, cumbuy):
        decide which calc_ to use
        if registrationlen>360 and cumbuy<=200:
            self.calc=self.calc_price1
        if registrationlen<=360 and cumbuy>200:
            self.calc=self.calc_price2
       else:
           self.calc=self.calc_price3
    def __call_*_(**kwargs):
        return self.calc(**kwargs)
    def calc_price1(registrationlen):
        ....
  1. All four calcs will always be performed
  2. Could you further explain?
  3. This I will know more on later
  4. Yes calculation "a", will be used in calculation "b"

2 The web interface has a controller layer, which performs the calculation.
In generally it is designed:

def return_price(Request):
    authorize
    validate request parameters
    perform data manipulation
    fill template variables
    render template
    return rendered html

The perform data manipulation line is where:
* Connect database
* Get data
* calculate
* store data
* return data to render

The calculation of which we are talking about is performed in the "calculate" line. The question is, should we design the calculate code so, that if some new formulas should be implemented, then we only have to modify this line.

If nothing else to be known of the task, and answering your original question, I think you should make a module that has pure functions. Pure functions are only dependent on the input and nothing else.

This article has been dead for over six months. Start a new discussion instead.