I have a procedure for sorting nodes in a node tree (VirtualTreeView) All memory leaks, extracted from FMM4 report, are stored in objects of a class TMemoryLeakList(these are the list I want to sort), which are stored in a list of lists called TGroupedMemoryLeakList, and both TMLL and TGMLL extend TObjectList. If I want to keep the functionality of being able to chose between ascending and descending sort order and choosing between sorting by one of four different data types, I 'have to' implement EIGHT different comparison methods (4 sort types * 2 sort directions) which I pass on to the main sorting method, because my TMLL list extends TObjectList. The main sorting method look like this.
The values for the fields fSortType and fSortDirection are acquired from the GUI comboboxes. One of those eight generic comparison functions looks like this. The seven remaining are copy/pasted variations of this one.
Is there any rational way to refactor this huge amount of copy paste code and still keep the functionality of choosing a specific sort type and direction?
SortListinstead ofSortand pass in areference tocompare function. That will accept methods of objects, or anonymous procs. And that way you can get your state into the compare function. Without being tempted to use global variables. Or you can useTObjectList<TMemoryLeak>and pass to theSortfunction anIComparer<TMemoryLeak>. Again you can pass the state in. What Delphi are you targeting? Either of these solutions are, in my view, better than anything usingContnrs.TObjectList. - David Heffernan