I am asking here something that is really haunting for years (for real !).
I guess in a "perfect world", we would have programs made of data models and functions, and those functions manipulate data with a total separation betweend data and code.
But I've got the feeling that in practice it seems impossible to achieve because we're always facing cases in which we have to manipulate data models, structures, or higher-order objects rather than just "raw data".
It is a bit confusing for me. I think the problem is very simple to understand but maybe a little less to explain, so I'm going to take an example :
Consider you have a data model like this (pseudo-code) :
Class Thing
{
int a;
int b;
string c;
}
Let's also consider we have a table containing rows of data following this data model, for instance :
+---+---+-------+
| a | b | c |
+---+---+-------+
| 1 | 2 | "ghi" |
+---+---+-------+
| 3 | 5 | "abc" |
+---+---+-------+
| 7 | 1 | "xyz" |
+---+---+-------+
| 2 | 8 | "def" |
+---+---+-------+
| 4 | 3 | "tuv" |
+---+---+-------+
This could be internally represented by an array of objects, each object being an instance of our Thing
class.
Now, we're in a very common situation where we want the end user able to see this data table on his screen and to sort rows according to a specific column.
For instance if the table would be ordered according to the b
field it would look like :
+---+---+-------+
| a | b | c |
+---+---+-------+
| 7 | 1 | "xyz" |
+---+---+-------+
| 1 | 2 | "ghi" |
+---+---+-------+
| 4 | 3 | "tuv" |
+---+---+-------+
| 3 | 5 | "abc" |
+---+---+-------+
| 2 | 8 | "def" |
+---+---+-------+
This means the user can ask the table to be ordered according to something which is not data, since the b
field is not data, it's an attribute/property.
Which implies, somewhere in the program we have a function that is able to sort the table according to a specific field.
Typically :
sortTable ( table , field , asc_or_desc )
But, here's the problem. If the table
argument of the sorting function corresponds to actual data (since it represents all the data rows of the table), what is the field
parameter ?
Certainly not data. It refers to an attribute/property of the table's row data model.
Functions are supposed to manipulate data, but here field
is related to code/structure of the program, not data.
- What are the possibilities to overcome this ?
- Should we hardcode every possible ordering function (like sortTableByA, sortTableByB, ...) ?
- Should we give up on separation of data and code principle ?
- Like doing some mapping between strings (data) and class attributes ?
- Or using "evil" things like
$$varname
in php orobj.getattr(attrname)
in python ? - Or maybe just considering that data models are also data and thus we can use classes or attributes as function parameters just like any other data (but doesn't this raise a problem of program design by mixing layers) ?
- Or am I just missing something fundamental at some point ?
Thank you