Save Calculation in Code or Database?

后端 未结 4 602
广开言路
广开言路 2021-01-14 09:27

I\'m setting up a system which will carry out various calculations on primitive data, and the provide an output based on the calculation.

My main question,

4条回答
  •  别那么骄傲
    2021-01-14 09:55

    If I understand your question, you've got a database containing domain data, and a lot of calculations you execute on that data. Currently, you store those calculations as strings in the database, and execute those calculations using eval().

    There are some reasons for doing this I can imagine - it's easy to share the calculations among different calculation instances (so you can run multiple parallel calculations, or create new calculation clients (e.g. a web client, a command line client, a mobile app). It also makes managing the calculations fairly easy - they all live in a single place.

    However, there are some obvious downsides:

    • you can't easily test a new calculation. You have to insert it into the database and then see if anything breaks.
    • an attacker who can insert rows into you calculation table can get you to execute arbitrary code.
    • logically, the domain data and the calculation logic are not the same thing.

    So, you have a bunch of alternatives. In similar scenarios, I've often created a folder in my application structure with the calculations, and used file streams to load the calculation code dynamically. By using a source code control system with automated deployments, you can deploy this to any number of calculation instances.

    For more complex scenarios, I've built a little domain specific language. This is perfectly possible in PHP. In your case, this would allow you to remove a lot of the housekeeping logic ($primBVal != 0) and focus on the domain. It's non-trivial, but if you have hundreds of calculations, it might be worth it.

提交回复
热议问题