Lists are extremely convenient for managing collections of things. Lets you write code that can handle as big or as small a collection as you like. No need to bury magic numbers in your code, remember the values of those numbers, or keep track of a bunch of symbolic constants. Example: today I write
Code: Select all
objref cells[100] // uh oh, magic numbers
for i = 0,99 cells[i] = new Pyr()
. . . many procs, funcs, and lines of code later . . .
// iterate over all cells
for i = 0,99 { // do I remember that the magic number was 100?
statements involvling cells[i]
}
Next week I decide to use a different number of cells. Do I remember to change every instance of 99 (or 100) to the correct value?
"Why not use a symbolic constant, like this:
NUMCELLS = 100
Then you can write
objref cells[NUMCELLS]
for i = 0,NUMCELLS-1
etc."
Fine, but suppose I need to manage many different collections of objects, and each collection has a different number of items in it? Then I will have code sprinkled with many different NUMthis and NUMthat, and I have to remember which NUMthis goes with what named array of this or that. Looks ugly.
Better to do this
Code: Select all
NUMCELLS = 100
objref cells
cells = new List()
for i = 0,NUMCELLS-1 cells.append(new Pyr())
Now I can iterate over all cells simply by
Code: Select all
for i=0,cells.count()-1 {
statements involving cells.o(i)
}
Still using symbolic constants, but only twice: once to define the constant and assign a value to it, and once to create that many instances of a particular class. After that, no need to remember magic numbers or clutter my code with silly names. If I want to change the number of items in any collection, simply change one assignment statement. But that's not all. The mere fact that the name of the list allows you to discover how many things are in it makes it possible to write generic procedures for iterating over sets--powerful abstractions that can be very helpful in program development.