13.07.2015 Views

Smalltalk Best Practice Patterns Volume 1: Coding - Free

Smalltalk Best Practice Patterns Volume 1: Coding - Free

Smalltalk Best Practice Patterns Volume 1: Coding - Free

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

ArrayYou need a Collection with a fixed number of elements. You may have been using anOrderedCollection.How do you store a collection with a fixed number of elements?OrderedCollection extols the virtues of flexibility. How many elements do you need? Why decidenow? Just use an OrderedCollection and avoid any arbitrary limits.What if you know when you create it exactly how big a collection will be? You could use anOrderedCollection and add elements, but the code would have lost the information that the size ofthe collection is fixed. Your code will communicate better if you say, “Here’s a collection. Here’show big it is. That won’t ever change.”The second reason to use a fixed size collection is efficiency. The flexibility of anOrderedCollection comes at the cost of an extra message to access elements. Most implementationsalso split OrderedCollections into two objects, so there is extra space overhead as well.Usually you don’t care about the efficiency, but I did one performance tuning gig where I got a40% speed up by replacing the OrderedCollections with Arrays. Of course, the code looked likeFORTRAN, not <strong>Smalltalk</strong>, but when you’re tuning performance you’re not out to save the world,just make it go a little faster.Use an Array. Create it with “new: anInteger” so that it has space for the number of elementsyou know it needs.Ward taught me the trick of simulating variable sized arrays. It is only valid if you are accessing theArray much more than you are adding to it and removing from it. Code that reads:children := OrderedCollection newyou change into:children := Array new “or even #()”When you need to add an element, instead of adding it to the collection:children add: anObjectyou allocate a new Array with the element added and assign it to the variable:children := children copyWith: anObjectSimilarly, for removing elements:children remove: anObjectyou allocate a new Array without the element:children := children copyWithout: anObjectUse a ByteArray to store SmallIntegers in the range 0..255. Use an Interval to represent an Array ofsequential Numbers. Use a RunArray to compactly store Arrays that have long runs of repeatedelements.<strong>Coding</strong> <strong>Patterns</strong> page 97 of 147 9/30/2006

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!