Daily stuff not frequently posted a software developer finds out or rants about.

Wednesday, April 25, 2007

A wizard for collections

Collections are a very helpful tool to manage small to medium-sized lists that are still small enough to be kept in memory, with comfortable methods to add, remove, sort, filter and more. The only downside of TCollection is that a unit containing the code for a simple collection, where each item has only a handful of properties, can be large and repetitious. And by saying large, I mean up to a thousand lines of code , which often lead me to using a quick but less comfortable TList or even TStringList hack - until I wrote a small utitiliy to help me create the two necessary classes with all their functions with just a few clicks.

Collection Templater shows you a list you can fill with a few property names and types and the names of the two relevant classes (descendants of TCollection and TCollectionItem), and uses a template to create the collection unit you want, including:
  • Sorting by each field
  • Filtering for each field
  • Loading from/Saving to .ini files
  • ToListItem methods for virtual TListViews
  • Switches to easily disable each of these features
  • JavaDoc style documentation on each function
  • Proper indent count everywhere (something the Delphi IDE still seems incapable of)
  • Template in external file do allow you to adjust it to your preferred formatting or to add more features (codetemplate.pas)
  • Both FreePascal and Delphi
The generated code (example here) is not perfect - you may want a different order for ListItem columns, it doesn't know comparison and assignment method for nontrivial types and a few minor things, but it'll place ToDo marks for these places so you'll easily find and finish them.

I might try to make a Delphi wizard out of it at some point, but since I don't know about such mechanisms for Lazarus and use it for both, that doesn't have a high priority.

Labels: , , ,