Tuesday, July 7, 2009

Favoring Data over Code

An old rule-of-thumb states that it's easier to modify data than code. So when a given feature can be accomplished by modifying data or modifying code one should tend to favor modifying data.

One implication of this heuristic for design is to create code so that some behavior can be modified without having to modify code. At the application level configuration files are one way to accomplish this. Preferences dialogs, also at the application level, are a more-user-friendly way to accomplish this.

This rule-of-thumb is often useful at the level of individual pieces of an application. TreeViews display representations of hierarchically related elements. When it comes to providing behavior based on different circumstances of the underlying element one can take a function-oriented approach or a data-oriented approach (or some other approach).

A function-oriented approach relies on function calls to examine the element in question along with as much context as is necessary to determine what action to take. This approach starts out being easier to code, especially when there isn't much information associated with each element. In the case of the tree view, having a function that parses the TreeNode.FullPath property to figure out the corresponding filesystem location is a function-oriented approach.

A data-oriented approach relies on each element carrying enough information so that it can be acted upon based on direct examination. With respect to the preceding example, a data oriented approach derives a class from TreeNode that stores its filesystem location. So the filesystem location can be examined directly instead of being computed.

The data oriented approach ends up being much easier to manage as more and more types are represented. The problem with the functional approach is that you often have to reinterpret the code long after you've forgotten its peculiarities because types tend to be added over time. Minimizing use of global state can make this easier but in the end it's still harder to parse logic than to interpret data that's much closer to the problem domain.

No comments :

Post a Comment