views:

151

answers:

2

I use Delphi, but this is a question that I think is valid for any object-oriented programming language.

When should I use records over objects. I used to think that you used records when you had some simple definition of a set of related data that you wanted to store together that didn't need to be able to manipulate itself. However every time I decided that a piece of data should be placed along with other data into a record, I came up with reasons for why it should be a fully blown object.

  1. There is almost always a reason that a piece of data needs some properties or methods.
  2. Memory management (creation and destruction) is much, much simpler with Objects (at least in Delphi).
  3. Using objects is probably no more expensive in terms of speed and memory but much much more flexible.

In fact I have recently come to the conclusion that possibly the only time you should use records over objects in modern applications is if you are reading a binary file from disk that can be read directly into an array of records.

I inherited a 10 year old project that uses records extensively over objects for small pieces of data, and I wonder is it just me or should these concepts be consigned to the recycle bin of experience.

Discuss.

+1  A: 
  1. When there are no methods to act upon your data, it is useless most of the time. So you are right here.

  2. One of the biggest differences between objects and records is the fact that records are default on the stack and objects on the heap. To get a record on the heap, you get all the hassle you were referring to, but when you can leave them on the stack it's a whole lot easier then managing objects lifetime. But lets face reality, there is little use for short lived records.

  3. When objects are instantiated, something more than merely reserving memory happens, there is a VMT to be managed, something a record hasn't. So it a little more expensive to allocate objects than records, but I suppose it is neglectable when your not talking about thousends of items.

To make your choice you need to consider how you will be using these objects or records. If you are going to read large binary files, records are the way to go (reading an entire buffer into an array of records maybe converting them to objects to work with). If you are handling structured data our runtime generated data objects seems to be a lot easier to work with.

Glenner003
A: 

If you are in a situation where you are really just dealing with data, then I think it's fine to use records.

Some typical scenarios:

  • Reporting
  • Batch updates
  • Binding name/value data to drop down lists in situations when building objects is just overkill.
  • In memory relational data cache
  • Performing operations on large amounts of data

However, as you pointed out these scenarios are in the minority in a typical OO application.

Daniel Auger