tags:

views:

119

answers:

2

I am refactoring some existing Delphi code into a class.

The current code uses a global variable defined as a dynamic array array of byte. At initialization time the code figures out the size of the array and uses SetLength to allocate it. It is convenient both as the buffer to obtain the data and as the runtime container for a later processing.

I want to move this variable as one of the object attributes.

But I am not sure if it is ok to maintain its type. Is it considered good practice?

The alternative I am considering is to tranform it to a dynamic container like a TList. I will keep the very same code for obtaining the data, with a local dynamic array but moving it to the container for the rest of its lifespan. Is it worth the effort? I know that elegance always pay off at the end, but I don't really see the value of the effort at this moment. Any thoughts?

+2  A: 

I know that elegance always pay off at the end,

Is that so? Note that changing working code always includes the risk to break something. It must IMHO be decided in every situation if the gained elegance is worth the risk.

In your case, if you add and remove items during runtime, I would use a TList since it is much easier for these operations. If you just initialize the length once and the arrays is constant after initialization you can just keep the dynamic array. There's definitely no "good practice" saying that you shouldn't use dynamic arrays.

Smasher
My first bet was to not touch the code. Your answer and Brian's has helped me make my final decision and leave the dynamic array in the object. Thanks.
PA
+2  A: 

Dynamic arrays are great, but really only for fixed dimentions. If they have to grow, especially in single record increments, this can cause eventual errors from the memory manager (and possible performance issues) since the array has to be reallocated and copied to the new bigger destination. TList does at least have a 'growing' mechanism that is called less frequently.

Brian Frost
Thanks, your insight is very valuable. Leaving the dynamic array, even if it could be argued against for elegance, has a technical reason now. Thanks.
PA
"this can cause eventual errors from the memory manager" Would you mind elaborating? What does that mean?
Allen Bauer