One of my students recently asked me an ORM related question . He had this little project he was working on to present in another class, and there was a little screen where he had some data. Let say he had a table with clients (relational, you may guess), and the client had a reference to the company table, since a client belongs to a company. Of course, the reference field in database was a Company ID.
His question was very simple, although very useful to explain some concepts on the spot. He was, of course, converting that client row into an object, to be later displayed in the little window. So he asked me: “Should I add a company ID attribute to the object, or should I add the company name directly?”. I looked at him and asked him back: “How do you feel by adding that ID to the object? Is it natural?” He glanced at his computer and then said… “No.”
Then we began to discuss. Actually, we started by defining what was that object’s function in the application, what was its role, what was it there for. The answer was very simple: it was there to provide info to the screen to display the data. Then, we went into discussing what the user needs, and the answer was the user needs the company name, not an ID. Lastly we went into discussing if we needed the tow objects, one Client object with a company ID and one Company object with a matching ID and a Name. We found out that, having those two objects, will require us to match them. That is a relational operation that was natural to the database. So, it was obvious we better let the database do its job and send us a new hybrid object with the client information and the company name already in place.
But wait a minute: It that ok? Weren’t we breaking the relational rules and normalization of the data? Thinking a couple of seconds I would say no. We weren’t.
Data is data, and it is stored and related in the database. You can process and produce new information by manipulating that data using the DB tools. That new information is not to store, but to consume by the business logic layers. That is BL information, it is not simple data anymore.
So the idea of ORM one-to-one does not fit in this example. If we have data and we have tools to process that and transform it into business information, then we should allow the BL layers to consume that BL info and not to spend cycles in processing, by hand, the data. Now the objects model the reality, not the data structure, and we work with cooked information and not raw data.
William Martinez Pomares.
Reference: An ORM Story