What's the difference between data and code?

前端 未结 13 793
青春惊慌失措
青春惊慌失措 2020-12-13 10:52

To take an example, consider a set of discounts available to a supermarket shopper.

We could define these rules as data in some standard fashion (lists of qualifyin

13条回答
  •  一个人的身影
    2020-12-13 11:26

    I would say that the distinction between data, code and configuration is something to be made within the context of a particular component. Sometimes it's obvious, sometimes less so.

    For example, to a compiler, the source code it consumes and the object code it creates are both data - and should be separated from the compiler's own code.

    In your case you seem to be describing the option of a particularly powerful configuration file, which can contain code. Much as, for example, the GIMP lets you 'configure' plugins using Scheme. As the developer of the component that reads this configuration, you would think of it as data. When working at a different level -- writing the configuration -- you would think of it as code.

    This is a very powerful way of designing.

    Applying this to the underlying question ("How would you code the above example?"), one option might be to adopt or design a high level Domain Specific Language (DSL) for specifying rules. At startup, or when first required, the server reads the rule and executes it.

    Provide an admin interface allowing the administrator to

    • test a new rule file
    • replace the current configuration with that from a new rule file

    ... all of which would happen at runtime.

    A DSL might be something as simple as a table parser or an XML parser, or it could be something as sophisticated as a scripting language. From C, it's easy to embed Python or Lua. From Java it's easy to embed Groovy or Clojure.

    You could switch in compiled code at runtime, with clever linking or classloader tricks. This seems more difficult and less valuable than the embedded DSL option, in my opinion.

提交回复
热议问题