Prefer data over functions

Eric Normand over at LispCast has a great post detailing his thoughts on why data should be preferred over functions, which in turn should be preferred over macros. If you’ve done functional programming in a Lisp before, you may have run into the design issue of whether to model your problem in terms of functions or data. For instance, let’s say you want to calculate the average of a set of numbers. You could easily do it in Clojure with functions:

(def numbers [1 2 3 4])
(/ (apply + numbers) (count numbers)) ; => 5/2

Alternatively, you could model it by creating a mini-DSL – custom data structures which are passed to an interpreter function to produce a result:

(def expression [:div [:add numbers] [:count numbers]])
(calculate expression) ; => 5/2

In this case, using functions gets the job done much faster, and is easier to understand. However, Eric argues why you might prefer using data:

  1. Structure of the data is transparent at runtime, allowing it to be inspected and analysed
  2. Data can be manipulated easily – most Lisps have a rich set of functionality for dealing with data structures
  3. Data can be interpreted in different ways
  4. DSLs allow a simpler semantic model to be imposed – this is usually the reason for writing a DSL in the first place and makes it easier to write custom tools such as editors

Eric pragmatically ends the discussion with his own personal guideline that code should be written as functions first, and then refactored to data only when the problem domain has been well understood. This helps to prevent cases where the DSL has to be extended in all kinds of clunky ways, because the problem domain expanded or was not covered adequately.

Link

Leave a comment