Carlo
Carlo

Reputation: 25959

Best practices to design classes to represent database tables

This may be a dumb question, but I've always wondered what's the best way to do this.

Suppose we have a database with two tables: Users and Orders (one user can have many orders), and in any OOP language you have two classes to represent those tables User and Order. In the database it's evident that the 'order' will have the 'user' ID because it's a one to many relationship (because one user can have many orders) and the user won't have any order ID. But in code what's the best practice out of the following three?

a) Should the user have an array of Orders?
b) Should the order have the user ID?
c) Should the order have a reference to the user object?

Or are there more efficient ways to tackle this? I've always done it in different ways, they all have both pros and cons, but I've never asked an expert's opinion.

Thanks in advance!

Upvotes: 3

Views: 486

Answers (2)

Mark Fraser
Mark Fraser

Reputation: 3198

You are asking about what is known as "object relational mapping" (ORM). I think the best way to learn what you want to learn is to look at some well established ORM libraries [such as ActiveRecord(Ruby) or Hibernate (Java)] and see how they do it.

With that in mind:

a) If the application requires it there should be access to an array (or similar enumeration) of objects representing the users orders through the user object. However this will usually best involve lazy loading (i.e. the orders will usually not be pulled from the database when the user pulled from the database....the orders will be subsequently queried when the application needs access to them). After objects are lazy loaded they can be cached by the ORM to eliminate the need for further queries on that istantiation.

b) Unless for performance reasons you only pull specific columns you're usually going to pull all columns when pulling an order. So it would include the user id.

c) Answer a applies to this as well.

Upvotes: 0

jamesmortensen
jamesmortensen

Reputation: 34038

In this instance, the User could have an array of orders if you're performing operations on the User that also involves orders that they own.

Whenever I design my classes, objects that are related contain pointers to each other, so I can access the Orders from the User and the User from an Order.

I don't believe there is a best practice as it really depends on what you're trying to accomplish. With Users and Orders, I could see you starting with an Order and needing to access the User and vice versa; therefore, in your situation it sounds like you should map the objects both ways.

One word of warning, just be careful not to create a circular reference. If you delete both objects without removing the reference, it could create a memory leak.

Upvotes: 1

Related Questions