re: Where to store the custom formula and how to substitute values at run-time?
I agree with the answers so far, in that the formula must be stored externally to the source code, in a database table or even a text file.
To substitute the values at run-time, you have a couple of options.
- Store the literal sql syntax
- Store a tokenized version of the sql
You also need to decide what to do with the operations. If you store the literal sql you can execute directly, you're good, but your end users have to learn sql syntax.
If you want to code a builder for them, you can have each operation in a row of a child table to the table with their userID.
Parent table has columns
userID
formulaID
formulaName
Child table has columns
userID
formulaID
operationSequence
field
operator
value
for your example,
(TotalAmount - Discount - SpecialDiscount) + Tax / 2
the rows in the child table would break down the calculation one arithmetic operation at a time:
userID formulaID operationSequence field operator value
1 1 1 tax / 2
1 1 2 netamount + totalAmount
1 1 3 netamount - discount
1 1 4 netamount - specialDiscount
your code knows to store the results of each operation in the netamount field.
If there's only a few things that vary with custom operations, such as the multiplier on the tax field, you could also just store that (1, 0.5, or 3.5 in your examples)